多重继承 菱形继承虚继承

//多重继承
#include<iostream>
using namespace std;
class Telephone
{
    public:
        Telephone()
        {
            cout << "Telephone构造"<< this << endl;
        }
        void call()
        {
            cout << "有服务吗" << endl;
        }
    int m_t;
};
class Camera
{
public:
    Camera()
    {
        cout << "Camera构造:" << this << endl;
    }
    void Photo()
    {
        cout << "马赛克" << endl;
    }
    int m_c;
};
class Ipod
{
public:
    Ipod()
    {
        cout << "Ipod构造:"<< this << endl;
    }
    void Music()
    {
        cout << "马赛克"<<endl;
    }
    int m_i;
};
class IPhone : public Telephone, public Camera, public Ipod
{
    public:
        IPhone()
        {
            cout << "IPhone构造"<< this << endl;
        }
}
int main()
{
    IPhone ipx;
    ipx.call();
    ipx.Photo();
    ipx.Music();
    Telephone* t = &ipx;  //Telephone *t (Telephone  *)&ipx;
    //Camera* c = ipx;
    //ipod* i = &ipx;
    //cout << t << “ ” << c << “  ” << i << “ ” << endl;
    //子类隐式转换成基类 从而实现皆然性
    //double b;
    //int *p=(int*)(&b);
    return 0;
}


//菱形(钻石)继承
class  A
{
public:
    A()
    {
        cout << “A构造” << this << endl;
    }
    void foo()
    {
        m_a = 10;
        cout << m_a << endl;
    }
    int m_a;
};
class   X :public A
{
public:
    X()
    {
        cout << “X构造” << this << endl;
    }
}
class   Y :public A
{
public:
    Y()
    {
        cout << “Y构造” << this << endl;
    }
}
class   Z :public X, public Y
{
public:
    Z()
    {
        cout << “构造” << this << endl;
    }
}
int main()
{
    Z z;
    z.foo();//调用不明确
    z.x::foo();
    z.y::foo();
    z.A::foo();//两个A会报错
    return 0;
}


//虚继承
class  A
{
public:
    A()
    {
        cout << "A构造" << this << endl;
    }
    void foo()
    {
        m_a = 10;
        cout << m_a << endl;
    }
    int m_a;
};
class   X :virtual public A
{
public:
    X()
    {
        cout << "X构造"<< this << endl;
    }
};
class   Y :virtual public A
{
public:
    Y()
    {
        cout << "Y构造" << this << endl;
    }
};
class   Z :public X, public Y
{
public:
    Z()
    {
        cout << "构造" << this << endl;
    }
};
int main()
{
    Z z;
    z.foo();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值