This question already has answers here:
default parameters in .h and .cpp files [duplicate]

(4个答案)


2年前关闭。




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

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所述),默认参数必须在进行调用的翻译单元中可见。如果将类拆分为grid_model.h和grid_model.cpp,则其他任何包含grid_model.h的.cpp(例如grid_model_test.cpp)都不会意识到仅存在于grid_model.cpp中的信息。

10-05 23:01
查看更多