C++實現(xiàn)動態(tài)綁定代碼分享
C++實現(xiàn)動態(tài)綁定代碼分享
#include <iostream> #include<string> using namespace std; class BookItem { private: string bookName; size_t cnt; public: BookItem(const string&s,size_t c,double p): bookName(s),cnt(c),price(p) {} ~BookItem(){} protected: double price; public: double bookPrice() { return this->price; } string getBookName() { return this->bookName; } size_t getBookCount() { return this->cnt; } virtual double money() { return cnt*price; } virtual void costMoney() { cout<<money()<<endl; } }; class BookBatchItem:public BookItem { private: string bookName; size_t cnt; public: BookBatchItem(const string&s,size_t c,double p,double discountRate): BookItem(s,c,p),cnt(c),discount(discountRate) {} ~BookBatchItem(){} private: double discount; public: double money() { if(cnt>=10) return cnt*price*(1.0-discount); else return cnt*price; } void costMoney() { cout<<money()<<endl; // cout<<cnt<<endl; // cout<<price<<endl; // cout<<discount<<endl; // cout<<"..."<<endl; } }; int main() { BookItem b1("Uncle Tom's house",11,12.5); b1.costMoney(); BookBatchItem b2("Gone with wind",11,12.5,0.12); b2.costMoney(); BookItem* pb=&b1; pb->costMoney(); pb=&b2; pb->costMoney(); return 0; }
只有采用“指針->函數(shù)()”或“引用.函數(shù)()”的方式調(diào)用C++類中的虛函數(shù)才會執(zhí)行動態(tài)綁定,非虛函數(shù)并不具備動態(tài)綁定的特征,不管采用任何方式調(diào)用都不行。
下面代碼中,一個java或者C#的程序員容易犯的一個錯誤。
class Base { public: Base() { p = new char ; } ~Base() { delete p; } private: char * p ; }; class Derived:public Base { public: Derived() { d = new char[10] ; } ~Derived() { delete[] d; } private: char * d ; }; int main() { Base *pA = new Derived(); delete pA ; Derived *pA = new Derived(); delete pA ; }
代碼中:
執(zhí)行delete pA時,直接執(zhí)行~Base析構函數(shù),不會執(zhí)行~Derived析構函數(shù)的,原因在于析構函數(shù)不是虛函數(shù)。
執(zhí)行delete pB時,先執(zhí)行~Derived()然后再執(zhí)行~Base()。
相比之下,java和C#中,所有的函數(shù)調(diào)用都是動態(tài)綁定的。
關于C++的成員函數(shù)調(diào)用與綁定方式,可以通過下面的代碼測試:
class Base { public: virtual void Func() { cout<<"Base"<<endl; } }; class Derived:public Base { public: virtual void Func() { cout<<"Derived"<<endl; } }; int main() { Derived obj; Base * p1 = &obj; Base & p2 = obj; Base obj2 ; obj.Func() ; //靜態(tài)綁定,Derived的func p1->Func(); //動態(tài)綁定,Derived的func (*p1).Func(); //動態(tài)綁定,Derived的func p2.Func(); //動態(tài)綁定,Derived的func obj2.Func(); //靜態(tài)綁定,Base的func return 0 ; }
可以看出“對象名.函數(shù)()”屬于靜態(tài)綁定,當然,使用指針轉換為對象的方式應該屬于指針調(diào)用那一類了,至于“類名::函數(shù)()”毫無疑問屬于靜態(tài)綁定。
相關文章
C++實現(xiàn)LeetCode(179.最大組合數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(179.最大組合數(shù)),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08使用設計模式中的單例模式來實現(xiàn)C++的boost庫
這篇文章主要介紹了使用設計模式中的單例模式來實現(xiàn)C++的boost庫的方法,其中作者對線程安全格外強調(diào),需要的朋友可以參考下2016-03-03