[問題] function override

看板C_and_CPP (C/C++)作者 (lalala)時間8年前 (2017/10/25 15:16), 編輯推噓1(105)
留言6則, 2人參與, 8年前最新討論串1/1
如果用base class的pointer指向child class的obj 呼叫virtual member function時會呼叫到child class的 如下面的example2 我的問題是如果要讓child member function覆蓋(override) base class裡的為什麼不直接宣告成child class? 這樣就可以直接覆蓋了,如example1, example3 缺點是什麼? 例如最常用來解釋多型的樂器的例子 class 樂器 { public:   virtual void Play( ); }; 然後讓 class 長笛 : public 樂器; class 鋼琴 : public 樂器; //方法一 樂器 *ptr=new 長笛; ptr->Play(); //為了可以執行到長笛裡的Play(吹)所以要用virtual delete ptr; ptr=new 鋼琴; ptr->Play(); //從吹長笛變成彈鋼琴 //方法二 長笛 *ptr=new 長笛 ptr->Play(); //不需要virtual關鍵字就可以override樂器class中的Play 鋼琴 *ptr2=new 鋼琴 ptr2->Play(); 方法二是不是就不算多型?而且是early binding? 什麼情況下一定要用方法一?或是方法一比起方法二有什麼優點? http://codepad.org/IJtr6CAS #include <iostream> using std::cout; using std::endl; class Base1{ public: int a; Base1():a(1){}; ~Base1(){}; void printA(){ cout<<"A:Base1, a="<<a<<endl; }; void printB(){ cout<<"B:Base1, a="<<a<<endl; }; virtual void printC(){ cout<<"C:Base1, a="<<a<<endl; }; }; class Derived1: public Base1 { public: int a; Derived1():a(2){}; ~Derived1(){}; void printB(){ cout<<"B:Derived1, a="<<a<<endl; }; void printC(){ cout<<"C:Derived1, a="<<a<<endl; }; }; int main(){ //example1 Derived1 test=Derived1(); test.printA(); //OUTPUT: A:Base1, a=1 test.printB(); //OUTPUT: B:Derived1, a=2 test.printC(); //OUTPUT: C:Derived1, a=2 cout<<test.a<<endl; //OUTPUT: 2 cout<<"----------------------------------------------"<<endl; //example2 Base1 *ptr=new Derived1; ptr->printA(); //OUTPUT: A:Base1, a=1 ptr->printB(); //OUTPUT: B:Base1, a=1 ptr->printC(); //OUTPUT: C:Derived1, a=2 cout<<ptr->a<<endl; //OUTPUT: 1 cout<<"----------------------------------------------"<<endl; //example3 Derived1 *ptrD=new Derived1; ptrD->printA(); //OUTPUT: A:Base1, a=1 ptrD->printB(); //OUTPUT: A:Derived1, a=2 ptrD->printC(); //OUTPUT: A:Derived1, a=2 cout<<ptrD->a<<endl; //OUTPUT: 2 return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.161.55.100 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1508915801.A.A84.html

10/25 15:25, 8年前 , 1F
假設你要寫一個演奏家的class,這個演奏家持有的樂器
10/25 15:25, 1F

10/25 15:25, 8年前 , 2F
是這個class的member virable,你會想宣告一堆不同樂
10/25 15:25, 2F

10/25 15:26, 8年前 , 3F
器的變數,還是用一種base樂器來表示就好?
10/25 15:26, 3F

10/25 21:31, 8年前 , 4F
呼叫大家都有的例如,呼叫你的左右手
10/25 21:31, 4F

10/25 21:32, 8年前 , 5F
但是肥宅可以呼叫錢包的特殊功能
10/25 21:32, 5F

10/25 21:33, 8年前 , 6F
而正妹則可以呼叫她去煮菜
10/25 21:33, 6F
文章代碼(AID): #1Py3fPg4 (C_and_CPP)
文章代碼(AID): #1Py3fPg4 (C_and_CPP)