C++完成靜態綁定代碼分享。本站提示廣大學習愛好者:(C++完成靜態綁定代碼分享)文章只能為提供參考,不一定能成為您想要的結果。以下是C++完成靜態綁定代碼分享正文
C++完成靜態綁定代碼分享
#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; }
只要采取“指針->函數()”或“援用.函數()”的方法挪用C++類中的虛函數才會履行靜態綁定,非虛函數其實不具有靜態綁定的特點,不論采取任何方法挪用都不可。
上面代碼中,一個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 ; }
代碼中:
履行delete pA時,直接履行~Base析構函數,不會履行~Derived析構函數的,緣由在於析構函數不是虛函數。
履行delete pB時,先履行~Derived()然後再履行~Base()。
比擬之下,java和C#中,一切的函數挪用都是靜態綁定的。
關於C++的成員函數挪用與綁定方法,可以經由過程上面的代碼測試:
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() ; //靜態綁定,Derived的func p1->Func(); //靜態綁定,Derived的func (*p1).Func(); //靜態綁定,Derived的func p2.Func(); //靜態綁定,Derived的func obj2.Func(); //靜態綁定,Base的func return 0 ; }
可以看出“對象名.函數()”屬於靜態綁定,固然,應用指針轉換為對象的方法應當屬於指針挪用那一類了,至於“類名::函數()”毫無疑問屬於靜態綁定。