结构何时需要默认构造函数



我编写了一个带有自定义构造函数的struct,该构造函数被设计为类的数据成员:

struct HP
{
int max_hp;
int hp;
// HP(){}; it is required for the next class constructor function. Why?
HP(int max_hp) {
this->max_hp=max_hp;
this->hp=max_hp;
}
};
class Character
{
protected:
HP hp;
friend struct HP;
public:
Character(int hp);
};

Character报告:Error C2512: 'HP': no appropriate default constructor available

Character::Character(int hp){
this->hp = HP(hp);
}

我在哪里隐式初始化HP,从而需要默认构造函数?inline

所有类成员在进入构造函数主体之前都已初始化。

Character::Character(int hp)
{ // already too late to initialize Character::hp
this->hp = HP(hp); // this is an assignment
}

如果没有HP默认构造函数,Character(int hp);就无法初始化其hp成员,除非它可以向HP构造函数提供参数,而将参数转发到HP构造函数的唯一方法是使用member Initializer List。

示例:

struct HP{
int max_hp;
int hp;
HP(int max_hp): // might as well use member initializer list here as well
max_hp(max_hp),
hp(max_hp)
{
// no need for anything in here. All done in Member Initializer List
}
};
class Character
{
protected:
HP hp;
friend struct HP; // not necessary. HP has no private members.
public:
Character(int hp);
};
Character::Character(int hp):
hp(hp)
{
}

最新更新