C++实现动态绑定代码分享
C++实现动态绑定代码分享
#include<iostream> #include<string> usingnamespacestd; classBookItem { private: stringbookName; size_tcnt; public: BookItem(conststring&s,size_tc,doublep): bookName(s),cnt(c),price(p) {} ~BookItem(){} protected: doubleprice; public: doublebookPrice() { returnthis->price; } stringgetBookName() { returnthis->bookName; } size_tgetBookCount() { returnthis->cnt; } virtualdoublemoney() { returncnt*price; } virtualvoidcostMoney() { cout<<money()<<endl; } }; classBookBatchItem:publicBookItem { private: stringbookName; size_tcnt; public: BookBatchItem(conststring&s,size_tc,doublep,doublediscountRate): BookItem(s,c,p),cnt(c),discount(discountRate) {} ~BookBatchItem(){} private: doublediscount; public: doublemoney() { if(cnt>=10) returncnt*price*(1.0-discount); else returncnt*price; } voidcostMoney() { cout<<money()<<endl; //cout<<cnt<<endl; //cout<<price<<endl; //cout<<discount<<endl; //cout<<"..."<<endl; } }; intmain() { BookItemb1("UncleTom'shouse",11,12.5); b1.costMoney(); BookBatchItemb2("Gonewithwind",11,12.5,0.12); b2.costMoney(); BookItem*pb=&b1; pb->costMoney(); pb=&b2; pb->costMoney(); return0; }
只有采用“指针->函数()”或“引用.函数()”的方式调用C++类中的虚函数才会执行动态绑定,非虚函数并不具备动态绑定的特征,不管采用任何方式调用都不行。
下面代码中,一个java或者C#的程序员容易犯的一个错误。
classBase { public: Base(){p=newchar;} ~Base(){deletep;} private: char*p; }; classDerived:publicBase { public: Derived(){d=newchar[10];} ~Derived(){delete[]d;} private: char*d; }; intmain() { Base*pA=newDerived(); deletepA; Derived*pA=newDerived(); deletepA; }
代码中:
执行deletepA时,直接执行~Base析构函数,不会执行~Derived析构函数的,原因在于析构函数不是虚函数。
执行deletepB时,先执行~Derived()然后再执行~Base()。
相比之下,java和C#中,所有的函数调用都是动态绑定的。
关于C++的成员函数调用与绑定方式,可以通过下面的代码测试:
classBase { public: virtualvoidFunc(){cout<<"Base"<<endl;} }; classDerived:publicBase { public: virtualvoidFunc(){cout<<"Derived"<<endl;} }; intmain() { Derivedobj; Base*p1=&obj; Base&p2=obj; Baseobj2; obj.Func();//静态绑定,Derived的func p1->Func();//动态绑定,Derived的func (*p1).Func();//动态绑定,Derived的func p2.Func();//动态绑定,Derived的func obj2.Func();//静态绑定,Base的func return0; }
可以看出“对象名.函数()”属于静态绑定,当然,使用指针转换为对象的方式应该属于指针调用那一类了,至于“类名::函数()”毫无疑问属于静态绑定。