默认参数值的位置是什么?只是在函数定义或声明中,还是两个地方都有?
当前回答
声明通常是最有用的,但这取决于你想如何使用这个类。
两者都是无效的。
其他回答
你可以任选其一,但不能两者兼得。通常在函数声明时这样做,然后所有调用者都可以使用该默认值。然而,你可以在函数定义中这样做,然后只有那些看到定义的人才能使用默认值。
c++将默认参数逻辑放在调用端,这意味着如果不能从调用端计算默认值表达式,则不能使用默认值。
其他编译单元通常只包含声明,因此放置在定义中的默认值表达式只能在定义编译单元本身中使用(并且在定义之后,即在编译器看到默认值表达式之后)。
最有用的地方是在声明(.h)中,这样所有用户都能看到它。
有些人也喜欢在实现中添加默认值表达式(作为注释):
void foo(int x = 42,
int y = 21);
void foo(int x /* = 42 */,
int y /* = 21 */)
{
...
}
然而,这意味着重复,并将增加注释与代码不同步的可能性(没有注释的代码会更糟糕吗?带有误导性注释的代码!)。
声明通常是最有用的,但这取决于你想如何使用这个类。
两者都是无效的。
如果函数是公开的——非成员的、公共的或受保护的——那么调用者应该知道它们,并且默认值必须在头文件中。
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个
我强烈建议您这样使用它