zoukankan      html  css  js  c++  java
  • 【c++】多层次继承类对象的构造函数参数的传递方法

    #include <iostream.h>
    //基类CBase
    class CBase
    {
        int a;
    public:
        CBase(int na)
        {
            a=na;
            cout<<"CBase constructor! ";
        }
        ~CBase(){cout<<"CBase deconstructor! ";}
        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! ";
        }
        ~CDerive(){cout<<"CDerive deconstructor! ";}
        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! ";
        }
        ~CSubDerive(){cout<<"CSubDerive deconstructor! ";}
        int GetC(){return c;}
        void show()
        {
            //因为是公有继承,子派生类可以访问其父类和父类的父类的公有成员函数
            cout<<"int the subderive class object : ";
            cout<<"a = "<<GetA()<<endl;
            cout<<"b = "<<GetB()<<endl;
            cout<<"c = "<<GetC()<<endl;
        }
    };
    
    void main()
    {
        CSubDerive obj(30,20,10);
    
        cout<<"call the display function of the object: ";
        obj.show();
    
        cout<<" call the interface function of the object: ";
        cout<<"a = "<<obj.GetA()<<endl;
        cout<<"b = "<<obj.GetB()<<endl;
        cout<<"c = "<<obj.GetC()<<endl;    
    }
         
         
    分析:
    1.运行结果如下:
        
       
    

      

  • 相关阅读:
    适配器模式
    注册模式
    工厂模式
    策略模式和注入控制反转
    验签
    php中加密和解密
    asp.net textbox keyup事件触发后台的textchange事件
    jquery $.post 返回json数据
    网页播放音频、视频文件——基于web的html 5的音乐播放器(转载)
    c# 柱状图(转载)
  • 原文地址:https://www.cnblogs.com/xuelisheng/p/9240192.html
Copyright © 2011-2022 走看看