为什么忽略我的默认参数?

时间:2018-03-26 00:32:45

标签: c++ optional-parameters

为什么忽略我的默认/可选参数?

grid_model.h

void GridModel::PrintGrid(bool flag = false) {
    // things...
}

grid_model.cpp

ns::GridModel* gm = new GridModel();
gm->PrintGrid(true); // works
gm->PrintGrid(); // doesn't work

grid_model_test.cpp

grid_model_test.cpp:22:12: error: no matching function for call to ‘ns::GridModel::PrintGrid()’
  gm->PrintGrid();
                 ^
In file included from grid_model_test.cpp:2:0:
grid_model.h:27:7: note: candidate: void ns::GridModel::PrintGrid(bool)
  void PrintGrid(bool);
       ^~~~~~~~~

错误:

#include <iostream>

class Thing {
public:
        void Whatever(bool);
};

void Thing::Whatever(bool flag = false) {
        std::cout << "Parameter was: " << flag << std::endl;
}

int main() {
        Thing* thing = new Thing();
        thing->Whatever();
        return 0;
}

当我在其他地方使用它们时,它们似乎工作正常。

ssh -o ConnectionAttempts=1 -o ConnectTimeout=10 user@IP exit

1 个答案:

答案 0 :(得分:3)

作为良好的设计实践,默认参数值应放在声明中,而不是放在实现中:

class GridModel {
public:
        GridModel();
        void PrintGrid(bool flag=false);
};

void GridModel::PrintGrid(bool flag) {
    // things...
}

从技术上讲(如此处http://en.cppreference.com/w/cpp/language/default_arguments更详细描述):默认参数必须在进行调用的翻译单元中可见。如果在grid_model.h和grid_model.cpp中拆分类,则包含grid_model.h的任何其他.cpp(例如grid_model_test.cpp)将不会知道仅存在于grid_model.cpp中的信息。