c++ 植物类 继承多态 菱形继承

#pragma once//头文件

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

//
// 1.实现以下几个类的成员函数
// 2.实现一个虚函数的覆盖及调用
// 3.处理菱形继承问题。
//

// 植物
class Botany
{
public:
	Botany(const string&  name);
	virtual ~Botany();
	virtual void Display();
	Botany(const Botany& b);
protected:
	string _name;//名字
	static size_t _sCount;
};

class Tree : public Botany
{
public:
	//...实现默认的成员函数

	Tree(const string&  name, const int hight);
	virtual void Display();
	virtual ~Tree();
	Tree(const Tree& t);
protected:
	int _hight;		// 高度
};

class Flower : public Botany
{
public:
	//...实现默认的成员函数
	Flower(const string&, const string&  color);
	virtual void Display();
	virtual ~Flower();
	Flower(const Flower& f);
protected:
	string _colour;	// 颜色
};

// 白兰花,即是树有时花。
class MicheliaAlba : public Flower, public Tree
{
public:
	MicheliaAlba(const string& name, const string& color, const int hight);
	virtual void Display();
	virtual ~MicheliaAlba();
	MicheliaAlba(const MicheliaAlba& m);
protected:
	// ...
};

#include <iostream>//函数文件
#include<string>
#include"plant.h"

using namespace std;

size_t Botany::_sCount = 0;

void Botany::Display()
{
	cout<<"Botany: "<< _name << endl;
	cout << _sCount << endl;

}


Botany::Botany(const string&  name)
	:_name(name)
{
	++_sCount;
	cout << "Botany" << endl;
}
Tree::Tree(const string&  name, const int hight)
	: Botany(name)
	, _hight(hight)
{
	cout << "Tree" << endl;
}

Flower::Flower(const string&  name, const string&  color)
	:Botany(name)
	,_colour(color)
{
	cout << "Flower" << endl;
}

MicheliaAlba::MicheliaAlba(const string&  name, const string&  color, const int hight)
	:Flower(name,color)
	, Tree(name,hight)
{
	cout << "MicheliaAlba" << endl;
}


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

void Flower::Display()
{
	cout << "Flower " << _name << endl;
	cout << _sCount << endl;

}

void MicheliaAlba::Display()
{
	cout << "MicheliaAlba " << Flower:: _name <<"  "<<Flower::_colour
		<<"  "<<Tree::_hight<< endl;
	cout << _sCount << endl;

}

 Botany::~Botany()
{
	 cout << "~Botany" << endl;
}

 Tree:: ~Tree()
 {
	 cout << "~Tree" << endl;
 }

 Flower:: ~Flower()
 {
	 cout << "~Flower" << endl;
 }

 MicheliaAlba::~MicheliaAlba()
 {
	 cout << "~MicheliaAlba" << endl;
 }

 Botany::Botany(const Botany& b)
	 :_name(b._name)
 { }

 Tree::Tree(const Tree& t)
	 : Botany(t._name)
	 , _hight(t._hight)
 { }

 Flower::Flower(const Flower& f)
	 : Botany(f._name)
	 , _colour(f._colour)
 { }

 MicheliaAlba::MicheliaAlba(const MicheliaAlba& m)
	 : Tree(m.Tree::_name,m._hight)
	 , Flower(m.Flower::_name,m._colour)
 { }
 
 #include <iostream>//主函数  测试文件
#include<string>
#include"plant.h"
using namespace std;

void test()
{
	MicheliaAlba m("白兰花", "红色",20);
	m.Display();
	MicheliaAlba m2(m);
	m2.Display();
	m.Display();
}

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


你可能感兴趣的:(c++;继承多态;菱形继承)