c++ -- 关于使用默认参数的困惑

标签 c++

<分区>

例如,有3个文件,sum.h , sum.cpp , 和 main.cpp .

sum.h --

    ...
    int sum (int, int, int);
    ...

sum.cpp

    ...
    int sum (int a, int b, int c=10) { 
       return a + b + c;
    }

main.cpp

   ...
   cout << sum (1, 2) << endl;
   ...

编译器抛出一个错误说 too few arguments to function... .

如果我编码为 cout << sum (1,2,3) << endl; 它工作正常 但是如何只传递 2 个参数呢?

最佳答案

默认函数参数必须放在调用站点看到的函数声明中。

int sum (int, int, int = 10);

它们在调用函数的表达式中是必需的。实现不应该关心它是否传递了默认值。

此外,您可以在更小的范围内重新声明函数,并给出完全不同的默认参数。此代码片段摘自 c++17 标准草案并演示了我的意思:

void f(int, int);
void f(int, int = 7);
void h() {
  f(3);                         // OK, calls f(3, 7)
  void f(int = 1, int);         // error: does not use default
                                // from surrounding scope
}
void m() {
  void f(int, int);             // has no defaults
  f(4);                         // error: wrong number of arguments
  void f(int, int = 5);         // OK
  f(4);                         // OK, calls f(4, 5);
  void f(int, int = 5);         // error: cannot redefine, even to
                                // same value
}
void n() {
  f(6);                         // OK, calls f(6, 7)
} 

理论上(在实践中不要这样做),您甚至可以使用不同的 header 来声明具有不同默认参数值的相同函数。只要它们不包含在同一个翻译单元中,它就会按预期工作。

关于c++ -- 关于使用默认参数的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40496913/

相关文章:

javascript - V8 引擎是否使用 C++ 替换了以前用 JavaScript 编写的部分代码库?

c++ - 指向相同内存位置但不同程序的指针

c++ - 在 OpenGL 中使用 std::vector 作为顶点/元素列表

c++ - memcpy 定义的位置

c++ - 如何使用 C++ 计算 1-100 数组中的覆盖百分比?

c++ - 如何在每个成员的基础上覆盖类范围的 __declspec(dllexport) 注释?

c++ - X 元素数组中的重复项

c++ - ‘type’ 中没有名为 ‘struct boost::enable_if<boost::is_pod<T>, void>’ 的类型

c++ - Python 中是否有类似于 C++ 中的结构的数据类型?

c++ - 函数指针