您的位置:首页 > 编程语言 > C语言/C++

POJ C++程序设计 编程题#3 编程作业—运算符重载

2015-08-24 09:36 1031 查看

编程题 #3

来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)

注意: 总时间限制: 1000ms 内存限制: 65536kB

描述

写一个二维数组类 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,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,


#include <iostream>
#include <cstring>
using namespace std;
// 在此处补充你的代码
class Array2 {
private:
int * a;
int i, j;
public:
Array2() {a = NULL;}
Array2(int i_, int j_) {
i = i_;
j = j_;
a = new int[i*j];
}
Array2(Array2 &t){
i = t.i;
j = t.j;
a = new int[i * j];
memcpy(a, t.a, sizeof(int)*i*j);
}
Array2 & operator=(const Array2 &t) {
if (a != NULL) delete []a;
i = t.i;
j = t.j;
a = new int[i*j];
memcpy(a, t.a, sizeof(int)*i*j);
return *this;
}
~Array2() {if (a != NULL) delete []a;}
// 将返回值设为int的指针,则可以应用第二个【】,不用重载第二个【】操作符
int *operator[](int i_) {
return a+i_*j;
}
int &operator()(int i_, int j_) {
return a[i_*j + 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;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: