C++类数组动态申请内存注意事项,构造函数需要初始化,否则会出现错误提示,可以在声明构造函数时对形参进行赋值,比如:Point(int px=0,int py=0),或者在构造函数体内进行赋值;此外,记得利用delete释放内存空间。
/*****2020.9.1****/
#include <iostream>
using namespace std;
class Point {
public:
/*公有接口*/
Point(int px=0 , int py=0 )
/*构造函数带默认形参值*/
{
x = px, y = py;
}
void init(int px,int py)
/*更新坐标值*/
{
x = px, y = py;
}
void print()
/*输出坐标值*/
{
cout << "(" << x << "," << y << ")" << endl;
}
private:
int x, y;
};
int main()
{
//Point pArray[5] = {Point(1,2),Point(1,2) ,Point(1,2) ,Point(1,2) ,Point(1,2) };
Point* pArray = new Point[5];
if (!pArray) {
cout << "allocation error!" << endl;
return -1;
}
int x, y;
for (int k =0; k < 5; k++) {
cin >> x >> y;
pArray[k].init(x, y);
}
cout << "Array of Point:" << endl;
for (int k = 0; k < 5; k++)
pArray[k].print();
delete[] pArray;
return(0);
}