017:二维数组类

描述

写一个二维数组类 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,

代码实现

实现代码如下图,

  1. 注意增加了有参构造函数,无参构造函数也要写一个,main函数中有调用无参构造函数生成对象
  2. 重载赋值运算符,不要忘了将本对象的原数组空间delete掉,再重新申请空间
  3. 因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; 
	}
};

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值