一、什么是堆对象
堆对象是指程序在运行过程中可以根据需要随时可以建立或删除的对象
又称为动态对象,分为New 和Delete
学过数据结构的同学都知道,malloc、free函数
那么
New就相当于malloc
Delete就相当于free
二、堆对象的使用
(1)New的使用
new <类型说明符>(<初始值表>)
(2)Delete的使用
delete <指针名>
三、堆对象的一个实例
代码块:
#include<iostream>
using namespace std;
class test
{
public:
test(int i,int j)//这是一个构造函数
{
A = j;
B = i;
cout<<"构造函数!\n"<<endl;
}
~test()//这是一个析构函数
{
cout<<"析构函数!\n"<<endl;
}
void print();//打印函数
private:
int A,B;//私有成员A,B
};
void test::print()//test类里面的打印函数
{
cout<<A<<"."<<B<<endl;
}
int main()
{
test *a1,*a2;//两个指向类 test对象的指针
a1 = new test(1,2);//用New 运算符给他们赋值,执行构造函数
a2 = new test(4,5);
a1->print();//打印
a2->print();
delete a1;//释放-》执行析构函数
delete a2;
return 0;
}
运行结果:
三、总结
堆对象类似于malloc和free
但比他们性能更优越一些
写起来更方便一些