描述
写一个二维数组类 Array2,使得下面程序的输出结果是:
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
程序:
#include <iostream>
#include <cstring>
using namespace std;
class Array2 {
// 在此处补充你的代码
};
int main() {
Array2 a(3,4);
int i,j;
for( i = 0;i < 3; ++i )
for( j = 0; j < 4; j ++ )
a[i][j] = i * 4 + j;
for( i = 0;i < 3; ++i ) {
for( j = 0; j < 4; j ++ ) {
cout << a(i,j) << ",";
}
cout << endl;
}
cout << "next" << endl;
Array2 b; b = a;
for( i = 0;i < 3; ++i ) {
for( j = 0; j < 4; j ++ ) {
cout << b[i][j] << ",";
}
cout << endl;
}
return 0;
}
样例输入
None
样例输出
0,1,2,3, 4,5,6,7, 8,9,10,11, next 0,1,2,3, 4,5,6,7, 8,9,10,11,
代码实现
实现代码如下图,
- 注意增加了有参构造函数,无参构造函数也要写一个,main函数中有调用无参构造函数生成对象
- 重载赋值运算符,不要忘了将本对象的原数组空间delete掉,再重新申请空间
- 因array类中有动态申请的内存,所以我们还需要新增一个析构函数,对象消亡前,析构函数会帮助我们清掉申请的内存空间
class Array2 {
// 在此处补充你的代码
public:
int *p;
int i;//行大小
int j;//列大小
//无参构造函数
Array2(){
p=NULL;
i=j=0;
}
Array2(int i,int j){
this->i=i;
this->j=j;
p=new int[i*j];
}
//重载[]
int * operator [](int a){
return p+a*j;
}
//重载()
int operator ()(int a,int b){
return *(p+a*j+b);
}
//重载赋值运算符
Array2 & operator =(Array2 & a){
if(a.p){//入参的数组不空
int m,n;
if(p)//将原数组释放
delete [] p;
p=new int[(a.i)*(a.j)];//重新申请和参数数组一样大小空间
i=a.i;//a对象要访问a对象的i成员,所以成员变量必须是public
j=a.j;
for(m=0;m<a.i;m++)//拷贝源数组内容到目标数组
for(n=0;n<a.j;n++)
*(p+m*j+n)=*(a.p+m*j+n);//这里a对象要访问本对象的j成员,所以成员变量必须是public
}else{//入参的数组为空
delete [] p;
p=NULL;
i=j=0;
}
return *this;
}
~ Array2(){
if(p)
delete [] p;
}
};