C++继承与构造函数、复制控制

        每个派生类对象由派生类中定义的(非static)成员加上一个或多个基类子对象构成,因此,当构造、复制、赋值和撤销派生类型对象时,也会构造、复制、赋值和撤销这些基类子对象。

        构造函数和复制控制成员不能继承,每个类定义自己的构造函数和复制控制成员。像任何类一样,如果类不定义自己的默认构造函数和复制控制成员,就将使用合成版本。

 

1:构造函数和继承

       派生类的构造函数受继承关系的影响,每个派生类构造函数除了初始化自己的数据成员之外,还要初始化基类。

 

        派生类的合成默认构造函数:除了初始化派生类的数据成员之外,它还初始化派生类对象的基类部分。基类部分由基类的默认构造函数初始化:

class father
{
public:
    int publ_i;
    father(int a=1, int b=2, int c=3):publ_i(a),priv_i(b), prot_i(c) 
    {
        cout << "father constructor" << endl;
    }
    virtual void display()
    {
        cout << "[father]publ_i is " << publ_i << endl;
        cout << "[father]priv_i is " << priv_i << endl;
        cout << "[father]prot_i is " << prot_i << endl;
    }
private:
    int priv_i;
protected:
    int prot_i;
};

class son: public father
{
public:
    void display()
    {
        cout << "[son]publ_i is " << publ_i << endl;
        cout << "[son]prot_i is " << prot_i << endl;
    }
};
int main()
{
    son ss1;
    ss1.display();
}

        执行”son ss1;”语句时,调用派生类son的合成的默认构造函数,该函数会首先调用基类的默认构造函数。上述代码的结果是:

father constructor
[son]publ_i is 1
[son]prot_i is 3


        如果派生类自己定义了构造函数,则该构造函数会隐式调用基类的默认构造函数:

class son: public father
{
public:
    son(int a = 2):mypriv_i(a)
    {
        cout << "son constructor" << endl;
    }
    void display()
    {
        cout << "[son]publ_i is " << publ_i << endl;
        cout << "[son]prot_i is " << prot_i << endl;
        cout << "[son]mypriv_i is " << mypriv_i << endl;
    }
private:
    int mypriv_i;
};

int main()
{
    son ss1;
    ss1.display();
}

        执行”son ss1;”语句时,调用派生类son的默认构造函数,该函数首先调用基类的默认构造函数初始化基类部分,然后,使用初始化列表初始化son::mypriv_i,最后,在执行son构造函数的函数体。上述代码的结果是:

father constructor
son constructo
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值