运算符重载编程题3(C++程序设计第4周)

来源:互联网 发布:centos如何安装deb文件 编辑:程序博客网 时间:2024/05/16 10:03

问题描述

写一个二维数组类 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;// 在此处补充你的代码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;}

输入

输出

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,

样例输入

样例输出

0,1,2,3,4,5,6,7,8,9,10,11,next0,1,2,3,4,5,6,7,8,9,10,11,

提示
提交作业时只提交补充的代码
源码

#include <iostream>#include <cstring>using namespace std;// 在此处补充你的代码class Array2{private:    int row;//数组行数    int column;//数组列数    int* ptr;//指向二维数组的指针public:    Array2()    {        ptr = NULL;    }    Array2(int paraRow, int paraColumn):row(paraRow),column(paraColumn)    {        ptr = new int[row * column];    }    Array2(Array2& a):row(a.row),column(a.column)    {        ptr = new int[row * column];        memcpy(ptr, a.ptr, sizeof(int)*row*column);    }    Array2& operator= (const Array2 &a)    {        if (ptr) delete[] ptr;        row = a.row;        column = a.column;        ptr = new int[row * column];        memcpy(ptr, a.ptr, sizeof(int)*row*column);        return *this;    }    ~Array2()    {        if (ptr) delete[] ptr;    }    int* operator [] (int i)    {        return ptr + i*column;//重载的实际上是第二维的[], 第一维的[]直接调用int型一维数组的定义    }    int& operator() (int i, int j)    {        return ptr[i*column + j];    }};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;}
0 0
原创粉丝点击