C++多继承语法

本文介绍了C++中多继承的基本概念及其实现方式,并通过具体代码示例展示了如何定义和使用多继承类。特别关注了当基类存在同名成员变量时如何正确访问的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

#include <iostream>
#include <string>

using namespace std;

//多继承

class Base1 {
public:
    Base1() {
        a = 100;
    }

    int a;
};

class Base2 {
public:
    Base2() {
        b = 200;
    }

    int b;
};

//子类 集成Base1和Base2
//语法  class 子类 :public 父类1,public 父类2...
class Son : public Base1, public Base2 {
public:
    Son() {
        c = 300;
    }

    int c;
};

void test() {
    Son s;
    cout << sizeof(s) << endl;
}

int main() {
    test();
    return 0;
}
12

#include <iostream>
#include <string>
using namespace std;

//多继承

class Base1 {
public:
    Base1() {
        a = 100;
    }

    int a;
};

class Base2 {
public:
    Base2() {
        a = 200;
        b = 200;
    }

    int a;
    int b;
};

//子类 集成Base1和Base2
//语法  class 子类 :public 父类1,public 父类2...
class Son : public Base1, public Base2 {
public:
    Son() {
        c = 300;
    }

    int c;
};

void test() {
    Son s;
    cout << sizeof(s) << endl;
    //当父类出现同名成员,需要加作用域区分
    cout << "base1 a=" << s.Base1::a << endl;
    cout << "base2 a=" << s.Base2::a << endl;
}

int main() {
    test();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值