动态数组类
如果我们的类中需要使用动态申请的内存空间,并且该空间是依附于对象的,我们一般在该类的构造函数中去申请空间(new),在该类的析构函数中释放空间(delete).
#include<iostream>
#include<cassert>
using namespace std;
class Point{
public:
Point():x(0),y(0){
cout<<"Default Constructor called."<<endl;
}
Point(int x,int y):x(x),y(y){
cout<<"Constructor called."<<endl;
}
~Point(){cout<<"Destructor called."<<endl;}
int getX() const{return x;}
int getY() const{return y;}
void move(int newX,int newY){
x=newX;
y=newY;
}
private:
int x,y;
};
//动态数组类
class ArrayOfPoints{
public:
ArrayOfPoints(int size):size(size){
points=new Point[size];
}
~ArrayOfPoints(){
cout<<"Deleting..."<<endl;
delete[]points;
}
//获得下标为index的数组元素
Point &element(int index){
assert(index>=0 && index<size);//如果数组下标不会越界,程序中止
return points[index];//*(points+index)
}
private:
Point *points;
int size;
};
int main(){
int count;
cout<<"Please enter the count of points:";
cin>>count;
ArrayOfPoints points(count);
points.element(0).move(5,10);//通过访问数组元素的成员
points.element(1).move(15,20);//通过类访问数组元素的成员
return 0;
}
动态申请多维数组(难点)
int *p=new int [6];
可以申请一个二维数组吗?
int *p=new int [2][3];
int *p=new int[2];
//int *p=new int [2][3];
在于他们返回的指针类型是不同的
int(*p)[3]=new int[2][3];
p=new int[size][3];
只有 第一维的容量可以使用变量,其他维度必须使用常量.
#include<iostream>
using namespace std;
int main(){
//int *p=new int[2];
//int *p=new int[2][3];
int (*p)[3];
int size=5;
p=new int[size][3];
//*(*(p+i)+j)
//p[i][j]
delete[]p;
}
#include<iostream>
using namespace std;
int main(){
float(*cp)[9][8]=new float[8][9][8];
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
for(int k=0;k<8;k++)
//以指针形式数组元素
*(*(*(cp+i)+j)+k)=static cast<float>(i*100+j*10+