未使用默认参数
default argument not being used
我正在调用这个函数
void Board::insertWord(const string& s, const Clue& clue,
bool recordLetters=true) {
...
}
这里insertWord( newWord, curClue );
,其中newWord
和curClue
分别为字符串和线索。我不明白为什么第三个参数不使用默认值。
g++ -c -std=c++11 -Wall -g board.cpp -o board.o
board.cpp: In member function ‘void Board::processUntilValid()’:
board.cpp:78:38: error: no matching function for call to ‘Board::insertWord(std::string&, const Clue&)’
insertWord( newWord, curClue );
^
board.cpp:78:38: note: candidate is:
In file included from board.cpp:1:0:
board.h:42:10: note: void Board::insertWord(const string&, const Clue&, bool)
void insertWord(const string& s, const Clue& c, bool recordLetters);
^
board.h:42:10: note: candidate expects 3 arguments, 2 provided
我没能重现这个问题。什么好主意吗?
This:
void Board::insertWord(const string& s, const Clue& clue,
bool recordLetters=true) { /* ... */ }
…为Board::insertWord
的定义。在c++中,定义方法时不需要添加默认参数,但是在声明方法时才需要添加默认参数,所以你的代码应该是:
class Board {
// Declaration:
void insertWord(const string& s, const Clue& clue,
bool recordLetters = true);
};
// Definition:
void Board::insertWord(const string& s, const Clue& clue,
bool recordLetters) { /* ... */ } // No default argument
默认参数属于声明(.h
)而不属于定义(.cpp
)。
默认实参是函数特定声明的属性,而不是函数本身的属性。每个调用方都根据它所看到的函数的声明来计算默认实参。
完全有可能(如果不明智的话)有这样的设置:
a.cpp
void foo(int i = 42);
void a()
{
foo();
}
b.cpp
void foo(int i = -42);
void b()
{
foo();
}
main.cpp
#include <iostream>
void a();
void b();
void foo(int i)
{
std::cout << i << 'n';
}
int main()
{
a();
b();
}
此程序将愉快地在一行输出42
,在下一行输出-42
,同时完全定义和符合。
因此,在您的例子中,您必须确保调用者能够访问定义默认实参的声明。在您的例子中,该声明恰好是函数定义。如果它隐藏在.cpp文件中,则可能需要将默认参数定义移到头文件中的函数声明中。
相关文章:
- 使函数参数默认为周围范围
- 如何将值传递给其参数(默认参数)
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- C ,构造器中允许的参考参数默认值
- 哪些规则控制参数默认赋值?
- 错误:上一个规范后给出的参数默认参数
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- C++模板参数默认函数实现
- QInput对话框参数默认值
- g++4.8.2上列表方法参数默认初始化时出错
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 函数模板:将第一个模板参数默认为第二个
- 模板模板参数默认可以引用其他模板类型的参数
- 参数默认为先例参数的值
- 如何修改一个类,使它只有一个成员函数,所有参数默认
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?
- 模板参数默认为更高版本