C++(40)多继承的二义性

概念:

如果一个派生类从多个基类派生,而这些基类又有一个共同的基类,则在对该基类中声明的名字进行访问时,可能产生二义性

示例

#include<iostream>
using namespace std;

class Parent
{
public:
    Parent(int a)
    {
        this->a = a;
        cout<<"Parent  构造函数被调用"<<endl;
    }
public:
    int a;
};

class Parent1:public Parent
{
public:
    Parent1(int b):Parent(1)
    {
        this->b = b;
        cout<<"Parent1  构造函数被调用"<<endl;
    }

    void print1()
    {
        cout<<"b = "<<b<<endl;
    }
public:
    int b;
};

class Parent2:public Parent
{
public:
    Parent2(int d):Parent(2)
    {
        this->d = d;
        cout<<"Parent2   的构造函数被调用"<<endl;
    }

    void print2()
    {
        cout<<"d = "<<d<<endl;
    }

public:
    int d;
};

class C:public Parent1,public Parent2
{
public:
    C(int e):Parent1(3),Parent2(4)
    {
        this->e = e;
        cout<<"C  构造函数被调用"<<endl;
    }
    void printC()
    {
        cout<<"e = "<<e<<endl;
    }

private:
    int e;
};



int main()
{
    C c(10);
    //c.a = 0;     error C2385: 对“a”的访问不明确
    c.Parent1::a = 10;
    return 0;
}

执行结果:
Parent  构造函数被调用
Parent1  构造函数被调用
Parent  构造函数被调用
Parent2   的构造函数被调用
C  构造函数被调用


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值