// 1.实现以下几个类的成员函数
// 2.实现一个虚函数的覆盖及调用
// 3.处理菱形继承问题。
//
// 植物
#include<iostream>
using namespace std;
#include<string>
class Botany
{
public:
Botany(string & name)
:_name(name)
{
++_sCount;
}
Botany& operator=(const Botany& b)
{
if(this != &b)
{
_name = b._name;
}
return *this;
}
~Botany()
{}
virtual void Display ();
protected:
string _name;
public:
static int _sCount;//名字
};
int Botany::_sCount = 0;
void Botany::Display()
{
cout<<"name:"<<_name<<endl;
}
class Tree : virtual public Botany
{
public:
Tree(string &name ,int hight )
:Botany(name)
,_hight(hight)
{}
Tree(const Tree &t)
:Botany(t)
,_hight(t._hight )
{}
Tree &operator=(const Tree &t)
{
if(this != &t)
{
Botany::operator =(t);
_hight = t._hight ;
}
return *this;
}
~Tree()
{}
virtual void Display ();
protected:
int _hight; // 高度
};
void Tree::Display()
{
cout<<"name: "<<_name<<endl;
cout<<"hight: "<<_hight<<endl;
}
class Flower :virtual public Botany
{
public:
//...实现默认的成员函数
Flower( string &name,string colour)
:Botany(name)
,_colour(colour)
{}
Flower(const Flower &f)
:Botany(f)
,_colour(f._colour )
{}
Flower &operator=(Flower &f)
{
if(this != &f)
{
Botany::operator =(f);
_colour = f._colour ;
}
return *this;
}
~Flower()
{}
virtual void Display ();
protected:
string _colour; // 颜色
};
void Flower::Display()
{
cout<<"name: "<<_name<<endl;
cout<<"color: "<<_colour<<endl;
}
// 白兰花,既是树又是花。
class MicheliaAlba : public Flower, public Tree
{
public:
void Display()
{
cout<<"name: "<<Flower::_name<<endl;
cout<<"hight: "<<Tree::_hight<<endl;
cout<<"Flower: "<<Flower::_colour <<endl;
}
private:
// ...
};
void Test()
{
string name = "Magnolia";
Tree t1(name,20);
t1.Display ();
Flower f1(name,"white");
f1.Display ();
cout<<"The num of botanies is: "<<Botany::_sCount<<endl;
}
int main()
{
Test();
return 0;
}继承&多态
最新推荐文章于 2025-03-23 17:50:13 发布
1540

被折叠的 条评论
为什么被折叠?



