如何在标题文件之外制作构造函数的定义

How to make the definition of the constructor outside the header file?

本文关键字:构造函数 定义 标题 文件      更新时间:2023-10-16

我在标题文件中具有此构造函数:

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