c++ - 如何在头文件之外定义构造函数?

标签 c++ constructor inline

我在头文件中有这个构造函数:

class Fan {
  Id id;
  string name;
  Age age;
public:
  Fan(Id id, string name, Age age);
};

.cpp 中的这个定义

Fan::Fan(Id id, string name="someone", Age age=0) : id(id), name(name),
  age(age), status(disconnected)
{
  if(id<0 || age<0) {
    throw BadParams();
  }
}

我有这个注释:(mtm 是命名空间)

..\Fan.h:60:2: note: mtm::Fan::Fan(mtm::Id, std::string, mtm::Age)
..\Fan.h:60:2: note:   candidate expects 3 arguments, 2 provided
..\Fan.h:47:7: note: mtm::Fan::Fan(const mtm::Fan&)
..\Fan.h:47:7: note:   candidate expects 1 argument, 2 provided

我试图在声明和定义之前内联并得到这个错误:

..\Fan.h:60:9: note: mtm::Fan::Fan(mtm::Id, std::string, mtm::Age)
..\Fan.h:60:9: note:   candidate expects 3 arguments, 2 provided
..\Fan.h:47:7: note: mtm::Fan::Fan(const mtm::Fan&)
..\Fan.h:47:7: note:   candidate expects 1 argument, 2 provided
..\Fan.h:60:9: warning: inline function 'mtm::Fan::Fan(mtm::Id, std::string, mtm::Age)' used but never defined [enabled by default]

最佳答案

您必须将默认参数放在声明中(即在 .h 文件中),而不是在 .cpp 文件中。

即:

class Fan {
public:
   Fan(Id id, string name="someone", Age age=0);
};

关于c++ - 如何在头文件之外定义构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243420/

相关文章:

python - Python 中的通用构造函数

c++ - 如何正确处理构造函数中的异常?

c++ - 如何用支持 __LINE__ 和 __FILE__ 的内联函数替换我的 C++ 异常宏?

Ruby slim 内联 if

php - 下载文件,但发送 POST 以启动它

c++ - LPCTSTR 到 LPCSTR 转换

c++ - 如何将应用程序的图像(HBITMAP)传输到另一个应用程序?

c++ - 使用构造函数继承来提供兄弟类型之间的转换

c++ - 所有文件的 Makefile

c++ - C++ 类对象的最佳容器