第十四周 【專案1-動物這樣叫】下面是給出的基類Animal宣告和main()函式。
阿新 • • 發佈:2019-01-07
#include <iostream> #include <string> using namespace std; class Animal { public: virtual void cry() { cout<<"不知哪種動物,讓我如何學叫?"<<endl; } }; class Mouse:public Animal { private: string name; char sex; public: Mouse(string nam,char se):name(nam),sex(se){} virtual void cry() { cout<<"該動物是老鼠,叫聲吱吱吱,性別是"<<((sex=='m')?"男":"女")<<"我的名字是"<<name<<endl; } }; class Cat:public Animal { private: string name; public: Cat(string nam):name(nam){} virtual void cry() { cout<<"該動物是貓,叫聲喵喵喵"<<"我的名字是"<<name<<endl; } }; class Dog:public Animal { private: string name; public: Dog(string nam):name(nam){} virtual void cry() { cout<<"該動物是狗,叫聲汪汪汪"<<"我的名字是"<<name<<endl; } }; class Giraffe:public Animal { private: string name; char sex; public: Giraffe(string nam,char se):name(nam),sex(se){}; virtual void cry() { cout<<"該動物是長頸鹿,叫聲沒有,我的性別是"<<((sex=='m')?"男":"女")<<"我的名字是"<<name<<endl; } }; int main( ) { Animal *p; p = new Animal(); p->cry(); Mouse m1("Jerry",'m'); p=&m1; p->cry(); Mouse m2("Jemmy",'f'); p=&m2; p->cry(); Cat c1("Tom"); p=&c1; p->cry(); Dog d1("Droopy"); p=&d1; p->cry(); Giraffe g1("Gill",'m'); p=&g1; p->cry(); return 0; }
執行結果
心得體會
開始的時候 竟然在忘了在class宣告結束後加分號。。。。結果可想而知 找了好久才找出來自己錯在了哪裡 以後做題要細心啊!!