C++学习 (3)--多重继承类对象的构造函数参数的传递方法

#include<iostream>
#include<stdio.h>
using namespace std;
/************************************************************************
* 多重继承(多层继承)
************************************************************************/
//基类CBase
class CBase
{
    int a;
public:
    CBase(int na)
    {
        a=na;
        cout<<"CBase constructor! " << endl;
    }
    ~CBase(){cout<<"CBase deconstructor! "<< endl;}
    int GetA(){return a;}
};

//CBase的派生类CDerive
class CDerive : public CBase
{
    int b;
public:
    //将参数na传递给基类CBase
    CDerive(int nb,int na):CBase(na)
    {
        b=nb;
        cout<<"CDerive constructor! "<< endl;
    }
    ~CDerive(){cout<<"CDerive deconstructor! "<< endl;}
    int GetB(){return b;}
};
//CDerive的派生类CSubDerive
class CSubDerive : public CDerive
{
    int c;
public:
    //向直接基类传递参数,不负责向间接基类传递参数
    CSubDerive(int nc,int nb,int na):CDerive(nb,na)
    {
        c=nc;
        cout<<"CSubDerive constructor! "<< endl;
    }
    ~CSubDerive(){cout<<"CSubDerive deconstructor! "<< endl;}
    int GetC(){return c;}
    void show()
    {
        //因为是公有继承,子派生类可以访问其父类和父类的父类的公有成员函数
        cout<<"int the subderive class object : "<< endl;
        cout<<"a = "<<GetA()<<endl;
        cout<<"b = "<<GetB()<<endl;
        cout<<"c = "<<GetC()<<endl;
    }
};

int main()
{
    CSubDerive obj(30,20,10);

    cout<<"call the display function of the object: "<< endl;
    obj.show();

    cout<<" call the interface function of the object: "<< endl;
    cout<<"a = "<<obj.GetA()<<endl;
    cout<<"b = "<<obj.GetB()<<endl;
    cout<<"c = "<<obj.GetC()<<endl;
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值