实际上无论是用基类还是派生类New, 结果是一样的:
#include <stdio.h> class Base { public: int a; Base(){ a=0; } virtual ~Base(){ printf("base delete"); } virtual void setA()=0; }; class A:public Base { public: A(){ a = 10; } ~A(){ printf("A class delete "); } virtual void setA() { a = 2; } }; class B:public Base { public: B(){ a=20; } ~B(){ a=-20; } virtual void setA() { a = 3; } }; int main() { Base *x = new A(); printf("BASE: a value of a construct %d ", x->a); x->setA(); printf("BASE: a value of a %d ", x->a); x = new B(); printf("BASE: b value of b construct %d ", x->a); x->setA(); printf("BASE: B value of b %d ", x->a); A *aClass = new A(); printf("a value of a construct %d ", aClass->a); aClass->setA(); printf("a value of a %d ", aClass->a); B *bClass = new B(); printf("b value of a construct %d ", bClass->a); bClass->setA(); printf("b value of a %d ", bClass->a); delete aClass; return 0; }
运行结果为: