C++中的菱形继承

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

class Botany
{
public:
Botany(const Botany& b1)//对象作为参数
:_name(b1._name)
{}

Botany(const char* ptr)//字符串作为参数
:_name(ptr)
{}

Botany& operator= (const Botany& b1)
{
if(this != &b1)
{
_name = b1._name;
}
return *this;
}

~Botany()
{}

virtual void Display ()
{
cout<<"Botany::Display"<<endl;
}

public:
protected:
string _name;
};

class Tree : virtual public Botany
{
public:
Tree(const string& name,int high)//字符串作为参数
:Botany(name.c_str())
,_hight(high)
{}

Tree(const Tree& b1)//对象作为参数
:Botany(b1)
{
_hight = b1._hight;
}

Tree& operator=(const Tree& t)
{
Botany::operator=(t);
_hight = t._hight;
return *this;
}
~Tree()
{}

virtual void Display ()
{
cout<<"Tree::Display"<<endl;
}

public:
int _hight;
};

class Flower : virtual public Botany
{
public:
Flower(const string& name,int colour)//字符串作为参数
:Botany(name.c_str())
,_colour(colour)
{}

Flower(const Flower& f)//对象作为参数
:Botany(f)//可以把一个派生类对象传递给基类对象
{
_colour = f._colour;
}

Flower& operator=(const Flower& f)
{
if(this != &f)
{
Botany::operator=(f);
_colour = f._colour;
}
}

~Flower()
{}

public:
protected:
int _colour;
};


class MicheliaAlba : public Tree, public Flower
{
public:
// 必须先初始化虚基类的构造函数
MicheliaAlba(const MicheliaAlba& m)//对象作为参数
:Botany(m)
,Tree(m)
,Flower(m)
{}

MicheliaAlba(const string& name,int high,int colour)//字符串作为参数
:Botany(name.c_str())
,Tree(name,high)
,Flower(name,colour)
{}

MicheliaAlba& operator=(const MicheliaAlba& m)//对象作为参数
{
if(this != &m)
{
Tree::operator =(m);
Flower::operator =(m);
}
return *this;
}
~MicheliaAlba()
{}

void Display()
{
cout<<Flower::_name<<endl;
cout<<Tree::_name<<endl;
}
};

void Test()
{
Botany b1("xxx");

}

int main()
{
Test();
MicheliaAlba m1("白玉兰", 10, 1);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值