一般来说,在创建子类对象时,先调用父类默认的构造函数,再调用子类的构造函数,如果父类的默认构造函数不存在编译器会自动生成一个。
但如果父类的默认构造函数是私有的或者被禁用了,而父类只存在一个有参构造函数。在子类创建对象时,无法调用父类的默认构造函数,这时候需要我们显式的调用父类的构造函数。
class Employee
{
private:
string name;
float salary;
public:
Employee() = delete;
Employee(const string &m_name, const float &m_salary = 10000) : name(m_name), salary(m_salary) {}
string getterName()
{
return name;
}
float getterSalary()
{
return salary;
}
void setterName(string m_name)
{
name = m_name;
}
void setterSalary(float m_salary)
{
salary = m_salary;
}
};
class Manager : public Employee
{
private:
string position;
float bonus;
public:
Manager() = delete;
Manager(string m_name, string m_position, float m_salary = 20000, float m_bonus = 0.1) : Employee(m_name, m_salary), position(m_position), bonus(m_bonus) {}
string getterPosition()
{
return position;
}
float getterBonus()
{
return bonus;
}
void setterPosition(string m_position)
{
position = m_position;
}
void setterBonus(float m_bonus)
{
bonus = m_bonus;
}
};
其实也就是通过函数初始化列表的方式调用父类的构造函数