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

编程题 #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,

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 // 在此处补充你的代码
 5 class Array2 {
 6 private:
 7     int * a;
 8     int i, j;
 9 public:
10     Array2() {a = NULL;}
11     Array2(int i_, int j_) {
12         i = i_;
13         j = j_;
14         a = new int[i*j];
15     }
16     Array2(Array2 &t){
17         i = t.i;
18         j = t.j;
19         a = new int[i * j];
20         memcpy(a, t.a, sizeof(int)*i*j);
21     }
22     Array2 & operator=(const Array2 &t) {
23         if (a != NULL) delete []a;
24         i = t.i;
25         j = t.j;
26         a = new int[i*j];
27         memcpy(a, t.a, sizeof(int)*i*j);
28         return *this;
29     }
30     ~Array2() {if (a != NULL) delete []a;}
31     // 将返回值设为int的指针,则可以应用第二个【】,不用重载第二个【】操作符
32     int *operator[](int i_) {
33         return a+i_*j;
34     }
35     int &operator()(int i_, int j_) {
36         return a[i_*j + j_];
37     }
38 };
39 
40 int main() {
41     Array2 a(3,4);
42     int i,j;
43     for( i = 0;i < 3; ++i )
44         for( j = 0; j < 4; j ++ )
45             a[i][j] = i * 4 + j;
46     for( i = 0;i < 3; ++i ) {
47         for( j = 0; j < 4; j ++ ) {
48             cout << a(i,j) << ",";
49         }
50         cout << endl;
51     }
52     cout << "next" << endl;
53     Array2 b; b = a;
54     for( i = 0;i < 3; ++i ) {
55         for( j = 0; j < 4; j ++ ) {
56             cout << b[i][j] << ",";
57         }
58         cout << endl;
59     }
60     return 0;
61 }
View Code

 

posted @ 2015-08-24 09:36  dagon  阅读(1649)  评论(3编辑  收藏  举报