編程題 #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 }
