堆对象的new与delete

 

直接贴代码:

//堆对象正确使用范例---1
#include
#include
using namespace std;

class A
{
public:
	A(){}
	A(int inum,string iname):num(inum),name(iname){}
	int getNum() const
	{
		return num; 
	}
	string getName() const
	{
		return name;
	}
	virtual void print() const
	{
		cout<<"num:"<print();

	b1->print();

	a1->destroy();

	b1->destroy();

	a1=NULL;
	b1=NULL;

	system("pause");
	return 0;
}


 

//堆对象正确使用范例---2
#include
#include
using namespace std;

class A
{
public:
	A(){}
	A(int inum,string iname):num(inum),name(iname){}
	virtual ~A(){}
	int getNum() const
	{
		return num; 
	}
	string getName() const
	{
		return name;
	}
	virtual void print() const
	{
		cout<<"num:"<print();

	b1->print();

	delete a1;//a1 b1 之间不存在关联,分别delete,如果存在 a1=b1,则只需delete a1 ,或delete b1
	delete b1;

	a1=NULL;
	b1=NULL;

	//堆对象---正确做法二
	A *a2=new A();

	B *b2=new B(201,"wangdan",78.1);

	a2=b2;

	a2->print();
	b2->print();

	delete a2;//a2 b2 之间存在关联,只需delete一个即可

	a2=NULL;
	b2=NULL;

	//桟对象---不需要delete,自动析构
	A a3(301,"baoyurong");
	B b3(301,"baoyurong",67.7);

	a3=b3;

	a3.print();//存在切分多态

	b3.print();

	//以下会出现错误
	A *a4=new A();

	B b4(401,"lianghao",23.9);

	a4=&b4;

	a4->print();
	b4.print();

	//delete a4;//delete 出错,出错原因在于,b4是桟对象,程序运行结束自动释放内存
	a4=NULL;

	system("pause");
	return 0;
}


 

你可能感兴趣的:(C++类与对象)