构造子类时,不可以在子类构造函数初始化列表中直接初始化父类的成员变量

问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值