未使用默认参数

default argument not being used

本文关键字:参数 默认 未使用      更新时间:2023-10-16

我正在调用这个函数

void Board::insertWord(const string& s, const Clue& clue, 
    bool recordLetters=true) {
  ...
}
这里

insertWord( newWord, curClue );

,其中newWordcurClue分别为字符串和线索。我不明白为什么第三个参数不使用默认值。

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文件中,则可能需要将默认参数定义移到头文件中的函数声明中。