2012 年
4.
#include <iostream>using namespace std;class A{public:A(int v1){f();}~A(){f();}void f(){++count;Show();}void Show(){cout<<"A::count="<<count<<endl;}protected:static int count;private:int x;};class B :public A{public:B(int v1,int v2):A(v1),y(v2){f();}~B(){f();}void f(){++count;Show();}void Show(){cout<<"B::count="<<count<<endl;}private:int y;};int A::count=0;int main(){A* p = new B(1,2);p->f();delete p;return 0;}
结果:
A::count=1B::count=2A::count=3A::count=4
反思:
1.指针不会创建对象的,指针只是创建一个大小为4字节的地址而已,和创建对象完全没有关系。
2.子类在构建的时候要先创建父类,先调用父类的构造函数
3.new出来的对象需要使用delete函数手动删除!!如果父类析构函数非虚函数,那么delete 父类指针就不会调用子类的析构函数!!!!!
