C++實現動態綁定代碼分享_C 語言

來源:互聯網
上載者:User

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

可以看出“對象名.函數()”屬於靜態繫結,當然,使用指標轉換為對象的方式應該屬於指標調用那一類了,至於“類名::函數()”毫無疑問屬於靜態繫結。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.