我在头文件中有这个构造函数:
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]
答案 0 :(得分:1)
您必须将默认参数放在声明中(即在.h文件中),而不是放在.cpp文件中。
即:
class Fan {
public:
Fan(Id id, string name="someone", Age age=0);
};