C++类继承--基类new和用派生类new的区别

实际上无论是用基类还是派生类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\n");
	}
	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\n", x->a);
	x->setA();
	printf("BASE: a value of a %d\n", x->a);

	x = new B();
	printf("BASE: b value of b construct %d\n", x->a);
	x->setA();
	printf("BASE: B value of b %d\n", x->a);

	A *aClass = new A();
	printf("a value of a construct %d\n", aClass->a);
	aClass->setA();
	printf("a value of a %d\n", aClass->a);
	
	B *bClass = new B();
	printf("b value of a construct %d\n", bClass->a);
	bClass->setA();
	printf("b value of a %d\n", bClass->a);
	
	delete aClass;
	
	return 0;
}

 运行结果为:

 

posted on 2018-05-24 17:49  Anlia  阅读(648)  评论(0编辑  收藏  举报

导航