堆对象的new与delete

 

直接贴代码:

//堆对象正确使用范例---1
#include<iostream>
#include<string>
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:"<<num<<" name:"<<name<<endl;
	}
	void destroy();
protected:
	virtual ~A(){}//此种析构方式,将不能构造桟对象
private:
	int num;
	string name;
};

void A::destroy()
{
	delete this;
}

class B:public A
{
public:
	B(){}
	B(int inum,string iname,float iscore):A(inum,iname),score(iscore){}
	virtual void print() const
	{
		cout<<"num:"<<getNum()<<" name:"<<getName()<<" score:"<<score<<endl;
	}
	void destroy();
protected:
	virtual ~B(){}//此种析构方式,将不能构造桟对象
private:
	float score;
};

void B::destroy()
{
	delete this;
}

int main()
{
	//堆对象
	A *a1=new A(102,"wangqian");

	B *b1=new B(101,"lanzhihui",89.7);

	a1->print();

	b1->print();

	a1->destroy();

	b1->destroy();

	a1=NULL;
	b1=NULL;

	system("pause");
	return 0;
}


 

//堆对象正确使用范例---2
#include<iostream>
#include<string>
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:"<<num<<" name:"<<name<<endl;
	}
private:
	int num;
	string name;
};

class B:public A
{
public:
	B(){}
	B(int inum,string iname,float iscore):A(inum,iname),score(iscore){}
	virtual ~B(){}
	virtual void print() const
	{
		cout<<"num:"<<getNum()<<" name:"<<getName()<<" score:"<<score<<endl;
	}
private:
	float score;
};

int main()
{
	//堆对象---正确做法一
	A *a1=new A(102,"wangqian");

	B *b1=new B(101,"lanzhihui",89.7);

	a1->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;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值