默认参数值的位置是什么?只是在函数定义或声明中,还是两个地方都有?


当前回答

声明通常是最有用的,但这取决于你想如何使用这个类。

两者都是无效的。

其他回答

默认参数值必须出现在声明中,因为这是调用者看到的唯一内容。

编辑:正如其他人指出的那样,你可以在定义上有争论,但我建议在编写所有代码时都认为这不是真的。

声明通常是最有用的,但这取决于你想如何使用这个类。

两者都是无效的。

如果函数是公开的——非成员的、公共的或受保护的——那么调用者应该知道它们,并且默认值必须在头文件中。

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.

好问题…… 我发现编码器通常使用声明来声明默认值。我一直坚持一种方式(或警告)或其他太基于编译器

void testFunct(int nVal1, int nVal2=500);
void testFunct(int nVal1, int nVal2)
{
    using namespace std;
    cout << nVal1 << << nVal2 << endl;
}

再加一分。带有默认参数的函数声明应该从右到左、从上到下进行排序。

例如,在下面的函数声明中,如果你改变了声明顺序,那么编译器会给你一个缺少默认参数的错误。编译器允许你在同一范围内将函数声明与默认参数分开,但它应该按照从右到左(默认参数)和从上到下(函数声明默认参数的顺序)的顺序进行。

//declaration
void function(char const *msg, bool three, bool two, bool one = false);
void function(char const *msg, bool three = true, bool two, bool one); // Error 
void function(char const *msg, bool three, bool two = true, bool one); // OK
//void function(char const *msg, bool three = true, bool two, bool one); // OK

int main() {
    function("Using only one Default Argument", false, true);
    function("Using Two Default Arguments", false);
    function("Using Three Default Arguments");
    return 0;
}

//definition
void function(char const *msg, bool three, bool two, bool one ) {
    std::cout<<msg<<" "<<three<<" "<<two<<" "<<one<<std::endl;
}