#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; }