C++实现动态绑定代码分享
发布时间:2020-12-16 05:54:33 所属栏目:百科 来源:网络整理
导读:C++实现动态绑定代码分享 #include iostream#includestringusing namespace std;class BookItem{private: string bookName; size_t cnt;public: BookItem(const stringpublic: double bookPrice() { return this-price; } string getBookName() { return thi
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,double p,double discountRate): BookItem(s,c,p),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",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 ; } 代码中: 关于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 ; } 可以看出“对象名.函数()”属于静态绑定,当然,使用指针转换为对象的方式应该属于指针调用那一类了,至于“类名::函数()”毫无疑问属于静态绑定。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |