默认参数值的位置是什么?只是在函数定义或声明中,还是两个地方都有?
当前回答
你可以使用任何一种(根据标准),但请记住,如果你的代码在包含default参数的定义之前看到了没有default参数的声明,那么编译错误就会出现。
例如,如果你包含头包含函数声明没有默认参数列表,因此编译器将寻找原型,因为它不知道你的默认参数值,因此原型将不匹配。
如果你把函数和默认参数放在定义中,那么包括这个文件,但我不建议这样做。
其他回答
默认参数值必须出现在声明中,因为这是调用者看到的唯一内容。
编辑:正如其他人指出的那样,你可以在定义上有争论,但我建议在编写所有代码时都认为这不是真的。
声明通常是最有用的,但这取决于你想如何使用这个类。
两者都是无效的。
如果函数是公开的——非成员的、公共的或受保护的——那么调用者应该知道它们,并且默认值必须在头文件中。
If the functions are private and out-of-line, then it does make sense to put the defaults in the implementation file because that allows changes that don't trigger client recompilation (a sometimes serious issue for low-level libraries shared in enterprise scale development). That said, it is definitely potentially confusing, and there is documentation value in presenting the API in a more intuitive way in the header, so pick your compromise - though consistency's the main thing when there's no compelling reason either way.
还有一点我没有发现任何人提到过:
如果你有虚方法,每个声明都可以有自己的默认值!
这取决于您调用的接口将使用哪个值。
ideone上的例子
struct iface
{
virtual void test(int a = 0) { std::cout << a; }
};
struct impl : public iface
{
virtual void test(int a = 5) override { std::cout << a; }
};
int main()
{
impl d;
d.test();
iface* a = &d;
a->test();
}
打印50个
我强烈建议您这样使用它
好问题…… 我发现编码器通常使用声明来声明默认值。我一直坚持一种方式(或警告)或其他太基于编译器
void testFunct(int nVal1, int nVal2=500);
void testFunct(int nVal1, int nVal2)
{
using namespace std;
cout << nVal1 << << nVal2 << endl;
}
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?
- 为什么std::map被实现为红黑树?