基类、子类、数据成员类对象三者 构造函数 的调用顺序

构造函数的调用顺序:基类 --> 数据成员类对象(基于声明的顺序) --> 子类;

析构函数的调用顺序则相反。

 

#include<iostream>
using namespace std;

class human
{
public:
    human(int height=0, int weight=0)
    {
        this->m_nHeight=height;
        this->m_nWeight=weight;
        cout<<"基类构造函数:human construct"<<endl;
    }

    ~human()
    {
        cout<<"基类析构函数:human destruct"<<endl;
    }

    void eat()
    {
        cout<<"human eat"<<endl;
    }

    void sleep()
    {
        cout<<"human sleep"<<endl;
    }

    void breathe()
    {
        cout<<"human breathe"<<endl;
    }

protected:
    int m_nHeight,m_nWeight;
};

class tool
{
public:
    tool()
    {
        cout<<"工具类tool:构造函数"<<endl;
        this->m_nName=-1;
        this->m_nPrice=-1;
    };

    ~tool(){cout<<"工具类tool:析构函数"<<endl;};

protected:
    int m_nPrice;
    int m_nName;
};

class tool2
{
public:
    tool2()
    {
        cout<<"工具类tool2:构造函数"<<endl;
        this->m_nName=-2;
        this->m_nPrice=-2;
    };

    ~tool2(){cout<<"工具类tool2:析构函数"<<endl;};

protected:
    int m_nPrice;
    int m_nName;
};

class male:public human
{
public:
    male()
    {
        m_nKind = -3;
        cout<<"子类构造函数:male construct"<<endl;
    }

    ~male()
    {
        cout<<"子类析构函数:male destruct"<<endl;
    }

protected:
    int m_nKind;
    tool2 m_t2;
    tool m_t;
};

int main(int argc,char* argv[])
{
    male f;//此处开始调动相关构造函数
    return 1;
}

//控制台输出如下:

//基类构造函数:human construct

//工具类tool2:构造函数(以类B、C对象作为类A的数据成员,则类对象B、C构造函数的调用顺序与该类数据成员在类A中声明顺序相关)

//工具类tool:构造函数

//子类构造函数:male construct



//子类析构函数:male destruct

//工具类tool:析构函数

//工具类tool2:析构函数

//基类析构函数:human destruct


 

可以看出: 默认构造函数或者是带默认参数的构造函数不仅对它本身、而且对复用它的其他类(子类或数据成员)都是及其关键的。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值