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

Why are my default parameters being ignored?

为什么我的 default/optional 参数被忽略了?

grid_model.h

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

grid_model.cpp

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

grid_model_test.cpp

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

错误:

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;
}

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

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

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

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