c++虚函数与多态实例分析
1 #include <iostream> 2 #include <complex> 3 using namespace std; 4 5 class Base 6 { 7 public: 8 Base() {cout<<"Base-ctor"<<endl;} 9 ~Base() {cout<<"Base-dtor"<<endl;} 10 virtual void f(int){cout<<"Base::f(int)"<<endl;} 11 virtual void f(double){cout<<"Base::f(double)"<<endl;} 12 virtual void g(int i=10){cout<<"Base::g()"<<i<<endl;} 13 }; 14 class Derived : public Base 15 { 16 public: 17 Derived() {cout<<"Derived-ctor" <<endl;} 18 ~Derived(){cout<<"Derived-dtor"<<endl;} 19 void f(complex<double>) { 20 cout<<"Derived::f(complex)"<<endl; 21 } 22 void g(int i=20){ 23 cout<<"Derived::g()"<<i<<endl; 24 } 25 }; 26 int main() 27 { 28 cout<<sizeof(Base)<<endl; //sizeof针对实例,不包含成员函数,每个实例都有虚函数表,子类共用父类的虚函数表所以sizeof大小一样 29 cout<<sizeof(Derived)<<endl; //至于为什么一个虚函数(注释掉两个)和三个虚函数的大小都是一样的,这是因为无论多少个虚函数,都保存在一个虚函数表中,而对象中只保存一个指向虚函数表的虚函数表指针,所以无论多少个虚函数,大小均为一个虚函数指针 30 31 Base b; 32 Derived d; 33 Base *pb=new Derived; //父类指针指向子类对象,多态的必要条件 34 b.f(1.0); 35 d.f(1.0); 36 pb->f(1.0); //并非多态,函数参数不同,为新的函数。 37 b.g(); 38 d.g(); 39 pb->g(); //多态,动态绑定,调用的为实际传给指针的类的方法 40 delete pb; 41 return 0; 42 }
1 #include <iostream> 2 using namespace std; 3 class Base 4 { 5 public: 6 Base():data(count) 7 { 8 cout<<"Base-ctor"<<endl; 9 ++count; 10 } 11 ~Base() 12 { 13 cout<<"Base-dtor"<<endl; 14 --count; 15 } 16 static int count; 17 int data; 18 }; 19 int Base::count; 20 class Derived : public Base 21 { 22 public: 23 Derived():data(count),data1(data) 24 { 25 cout<<"Derived-ctor"<<endl; 26 ++count; 27 } 28 ~Derived() 29 { 30 cout<<"Derived-dtor"<<endl; 31 --count; 32 } 33 static int count; 34 int data1; 35 int data; 36 }; 37 int Derived::count=10; 38 int main() 39 { 40 cout<<sizeof(Base)<<endl; 41 cout<<sizeof(Derived)<<endl; 42 43 Base* pb = new Derived[3]; 44 cout<<pb[0].data<<endl; 45 cout<<pb[1].data<<endl; 46 cout<<pb[2].data<<endl; //为什么它是10 不懂... 47 cout<<((static_cast<Derived*>(pb))+2)->data1<<endl; 48 delete[] pb; //由于析构函数不是虚函数,所以delete只执行了基类的析构函数,无法执行子类的析构函数 所以子类的count为13 49 50 cout<<Base::count<<endl; 51 cout<<Derived::count<<endl; 52 return 0; 53 }
参考资料:http://blog.csdn.net/hackbuteer1/article/details/7883531