📄 demo_object_new_delete_3.cpp
字号:
//***************************************************
// 由于分配数组时,new的格式是类型后面跟[元素个数],
// 不能再跟函数参数,所以,从堆上分配对象数组,只能
// 调用默认的构造函数,不能调用其他任何构造函数。
// 如果该类没有默认构造函数,则不能分配对象数组。
//***************************************************
# include <iostream.h>
# include <stdlib.h>
class Point
{
public:
Point()
{
X=Y=0;
cout<<"Default Constructor called."<<endl;
}
Point(int xx,int yy)
{
X=xx;
Y=yy;
cout<< "Constructor called."<<endl;
}
~Point()
{
cout<<"Destructor called."<<endl;
}
int GetX() { return X; }
int GetY() { return Y; }
void Move(int x,int y) { X=x; Y=y; }
private:
int X,Y;
};
int main()
{
Point *Ptr=new Point[2]; //创建对象数组
if(Ptr==NULL)
{
cout<<"Can't allocate more memory,terminating.\n";
exit(1);
}
Ptr[0].Move(5,10); //通过指针访问数组元素的成员
Ptr[1].Move(15,20); //通过指针访问数组元素的成员
cout<<"Deleting..."<<endl;
delete []Ptr; //删除整个对象数组
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -