动态多态
与继承中限定让父类参与但可以带入子类的方法一致
地址软绑定,由输入的决定
class father { public: virtual void speak() { cout<<"father!"; } }; class son:public father { public: void speak() { cout<<"son!"; } }; void spk(father &f) { f.speak(); } int main() { son s; spk(s); }
|
如此,要满足:1.包含继承 2.重写父类函数
使用时形参为父类的引用/指针
虚函数的用法
class father { public: virtual void speak() { cout<<"father!"; } }; class son1:public father { public: void speak() { cout<<"son1!"; } }; class son2:public father { public: void speak() { cout<<"son2!"; } }; int main() { father * a=new son1; a->speak(); a=new son2; a->speak(); delete a; }
|
纯虚函数
class father { public: virtual void speak()=0; }; class son1:public father { public: void speak() { cout<<"son1!"; } }; class son2:public father { public: void speak() { cout<<"son2!"; } }; int main() { father * a=new son1; a->speak(); a=new son2; a->speak(); delete a; }
class cc { public: virtual int caclute() { return 0; } } class cb:public cc; class cb:public cc;
|
纯虚析构函数
class father { public: father () { cout<<"大的活了"<<endl; } virtual ~father()=0; virtual void speak()=0; }; class son1:public father { public: void speak() { cout<<"son1!"; } son1 () { cout<<"小的活了"<<endl; } ~son1() { cout<<"小的似了"<<endl; } }; father::~father() { } int main() { father * a=new son1; a->speak(); delete a; }
|