问题
class Base
{
public:
int m_id;
Base(int id=0)
: m_id{ id } {}
int getId() const { return m_id; }
};
// 正确的写法
class Derived: public Base
{
public:
double m_cost;
Derived(double cost=0.0)
: m_cost{ cost } {}
double getCost() const { return m_cost; }
};
//错误的写法
class Derived: public Base
{
public:
double m_cost;
Derived(double cost=0.0, int id=0)
// does not work
: m_cost{ cost }, m_id{ id } {} //不可以在初始化列表里面直接初始化父类成员
double getCost() const { return m_cost; }
};
这是由于考虑到:如果父类成员是const成员,则在创建之时已经确定了它的值,如果允许在子类中再次赋值,与其定义冲突。
另一种正确的写法是使用委托构造函数:
class Derived: public Base
{
public:
double m_cost;
Derived(double cost=0.0)
: Base(0), m_cost{ cost } {}
double getCost() const { return m_cost; }
};
Reference:
Calling the base class constructor from the derived class constructor
Delegation and Calling Parent Class Constructors: How do I do both?
Constructors and initialization of derived classes