11.6.7重学C++之【多继承语法】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;



/*
    4.6.7 多继承语法
        实际开发中不建议使用多继承
        多继承可能引发父类中有同名成员出现,需要加作用域区分
        class 子类 : 继承方式 父类1, 继承方式 父类2, ...
*/



class Base1{
public:
    int a;

    Base1(){
        a = 100;
    }
};



class Base2{
public:
    int a;
    int b;

    Base2(){
        a = 50;
        b = 100;
    }
};



class Son : public Base1, public Base2{
public:
    int c;
    int d;

    Son(){
        c = 300;
        d = 400;
    }
};



void test1(){
    Son s;
    cout << "size of son = " << sizeof(s) << endl; // 16字节

    // 当多个父类出现同名成员,需要加作用域来区分
    cout << s.Base1::a << endl;
    cout << s.Base2::a << endl;
    //多继承容易产生成员同名的情况
    //通过使用类名作用域可以区分调用哪一个基类的成员
}





int main()
{
    test1();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114926526
今日推荐