#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
14-25.2堆中数组对象
注意对比小节“C++ 数组 2--1堆中数组对象 new申请的空间在堆中,即申请动态内存”
---------------------------------*/
class area
{
public:
area()
{
length=0; width=0;
// cout<<"调用构造函数设置,长:"<<length<<" 宽:"<<width<<endl;
}
~area()
{ cout<<"调用析构函数,释放内存,长:"<<length<<" 宽:"<<width<<endl;}
int get()
{return length*width;}
void set(int l,int w)
{
length=l;width=w;
cout<<"调用set函数设置,长:"<<length<<" 宽:"<<width<<endl;
}
private:
int length;
int width;
};
int main()
{
int i;
// area *one[5]; //定义指针数组 每个元素是一个指针(指向area类的对象)
area *one=new area[5]; //定义一颗指针或者一个数组名 每个元素是一个变量(存放area类的对象)
for(i=0;i<5;i++)
{
one[i].set(10,5*i);
cout<<"one["<<i<<"]:";
cout<<one[i].get()<<endl;
}
delete []one; //释放数组整个内存空间
return 0;
}
运行结果:
调用set函数设置,长:10 宽:0
one[0]:0
调用set函数设置,长:10 宽:5
one[1]:50
调用set函数设置,长:10 宽:10
one[2]:100
调用set函数设置,长:10 宽:15
one[3]:150
调用set函数设置,长:10 宽:20
one[4]:200
调用析构函数,释放内存,长:10 宽:20
调用析构函数,释放内存,长:10 宽:15
调用析构函数,释放内存,长:10 宽:10
调用析构函数,释放内存,长:10 宽:5
调用析构函数,释放内存,长:10 宽:0
Press any key to continue
C++ 数组 2--2堆中数组对象 动态申请一定大小的数组空间
最新推荐文章于 2021-09-05 21:37:48 发布