c++ - 为什么我的默认参数被忽略?

标签 c++ optional-parameters

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

grid_model.h

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

网格模型.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 中的信息。

关于c++ - 为什么我的默认参数被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49482420/

相关文章:

c++ - 如何用结构体数组制作菜单(lua代码转c++代码)

c++ - Visual Studio 无法识别某些类

Fortran 2003/2008 : Elegant default arguments?

go - 可变参数函数是可选参数的合适解决方案吗?

c++ - 我可以在没有虚拟微型端口驱动程序的情况下创建 VPN 应用程序吗?

c++ - vector 循环的起始值

python - 在Python中的方法调用中选择设置一些类属性的便捷方法

c# - 如何使用 Entity Framework 在具有多个联接的查询中使用可选参数?

java - 在不支持的语言中添加可选参数时,最好的设计是什么?

c++ - 当我的代码在函数范围之外时,为什么会出现编译器错误 "does not name a type"?