所以我有以下简单设置。
.HPP
class User {
std::string firstName;
std::string lastName;
std::string email;
std::string phoneNr;
public:
User(std::string firstName, std::string lastName, std::string email);
User(std::string firstName, std::string lastName, std::string email,
std::string phoneNr);
friend std::ostream& operator<<(std::ostream &o, User &u);
};
的.cpp
User::User(std::string fName, std::string lName, std::string email)
:firstName(fName),lastName(lName),email(email){
}
//Works
User::User(std::string fName, std::string lName, std::string email,
std::string phoneNr)
:firstName(fName), lastName(lName),email(email),phoneNr(phoneNr){
}
//Does not work
User::User(std::string fName, std::string lName, std::string email,
std::string phoneNr){
User(fName,lName,email,phoneNr);
this->phoneNr = phoneNr;
}
std::ostream& operator<<(std::ostream &a, User &b){
a<<b.firstName<<" "<<b.lastName<<std::endl;
a<<b.email<<std::endl;
a<<b.phoneNr<<std::endl;
}
现在,为什么我委托给第一个构造函数的第二个构造函数的实现会将字段留空?这对我来说没什么意义,第一个构造函数被调用(由打印输出验证),但它没有初始化任何东西。
这是否意味着我被迫在c ++中对所有构造函数使用列表初始化,如果它们必须委托给列表初始化构造函数?
答案 0 :(得分:1)
委托构造函数应该是:
User::User(std::string fName, std::string lName, std::string email, std::string phoneNr) : User(fName, lName, email, phoneNr)
{
this->phoneNr = phoneNr;
}
BTW,在您的情况下,您可能只使用一个默认参数
的构造函数User::User(std::string firstName, std::string lastName, std::string email, std::string phoneNr = "") :
firstName(fName), lastName(lName), email(email), phoneNr(phoneNr)
答案 1 :(得分:1)
委派应该在成员初始化列表中进行。您只是创建一个User
临时。这是固定语法:
User::User(std::string fName, std::string lName, std::string email,
std::string phoneNr) :
User(fName,lName,email)
{
this->phoneNr = phoneNr;
}