C++虚函数
#include<iostream> using namespace std; class ClaA { public: //virtual int a() = 0; //纯虚函数,类(抽象类)不能被实例化 virtual int a(){return 3;} virtual int b(){return 3;} int add(){return a()+b();} }; //具体类 class ClaB : public ClaA { public: virtual int a(){return 1;}//virtual可省略 virtual int b(){return 1;} }; class ClaC : public ClaA { public: int a(){return 2;} int b(){return 2;} }; //动态绑定(后期绑定),虚函数表(vtable) int adds(ClaA *a){ return a->add(); } int main() { ClaC c; ClaB d; cout<<adds(&c)<<","<<adds(&d)<<endl;//4,2 cout<<sizeof(ClaA)<<","<<sizeof(ClaB)<<endl;//4,4:vptr占用 return 0; }
Meet so Meet.
C plusplus
I-PLUS....