直接贴代码:
//堆对象正确使用范例---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;
}