通过和大家的讨论,受益匪浅。再次谢谢大家的热情。
//filename: arr2d.h #ifndef ARR2D_H_ #define ARR2D_H_ #include <iostream> class Arr2D { private: int xSize; int ySize; struct Coor { int x; int y; int v; }; Coor* unit; public: Arr2D(); Arr2D(int x_size, int y_size); ~Arr2D(); void showValue(int x_at, int y_at)const; int getValue(int x_at, int y_at)const; void setValue(int x_at, int y_at, int v_set_to); }; #endif
//filename: arr2d.cpp #include "arr2d.h" Arr2D::Arr2D() { xSize = 0; ySize = 0; Coor* temp = new Coor[0]; unit = temp; } Arr2D::Arr2D(int x_size, int y_size) { xSize = x_size; ySize = y_size; int dataSize = xSize * ySize; Coor* temp = new Coor[dataSize]; for (int i = 0; i < xSize; i++){ for (int j = 0; j < ySize; j++){ int sn = ySize * i + j; temp[sn].v = 0; temp[sn].x = i; temp[sn].y = j; } } unit = temp; } Arr2D::~Arr2D() { delete [] unit; } void Arr2D::showValue(int x_at, int y_at)const { for (int i = 0; i < xSize; i++){ for (int j = 0; j < ySize; j++){ int sn = ySize * i + j; if ( unit[sn].x == x_at && unit[sn].y == y_at){ std::cout << "unit[" << unit[sn].x << "," << unit[sn].y << "] = " << unit[sn].v << std::endl; } } } } int Arr2D::getValue(int x_at, int y_at)const { for (int i = 0; i < xSize; i++){ for (int j = 0; j < ySize; j++){ int sn = ySize * i + j; if ( unit[sn].x == x_at && unit[sn].y == y_at){ return unit[sn].v; } } } return 0; } void Arr2D::setValue(int x_at, int y_at, int v_set_to) { for (int i = 0; i < xSize; i++){ for (int j = 0; j < ySize; j++){ int sn = ySize * i + j; if ( unit[sn].x == x_at && unit[sn].y == y_at){ unit[sn].v = v_set_to; } } } }
//filename: main.cpp //使用下面语句可创建 X_SIZE * Y_SIZE 的二维数组: //Arr2D objName ( X_SIZE, Y_SIZE ); //使用下面成员函数将二维数组的x,y位置赋值为A; //objName.setValue(x,y,A); //使用下面成员函数可返回二维数组x,y处的值 //objName.getValue(x,y); //使用下面成员函数可直接显示二维数组x,y处的值 //objName.showValue(x,y); #include "arr2d.h" int main(int argc, char* argv[]) { int const X_SIZE = 3; int const Y_SIZE = 4; Arr2D test ( X_SIZE, Y_SIZE ); for (int i = 0; i < X_SIZE; i++){ for(int j = 0; j < Y_SIZE; j++){ test.setValue(i,j,100+Y_SIZE*i+j); } } test.setValue(1,1,200); test.setValue(2,2,300); for (int i = 0; i < X_SIZE; i++){ for(int j = 0; j < Y_SIZE; j++){ test.showValue(i,j); } } int test_get = test.getValue(2,2); std::cout << "test_get = " << test_get << std::endl; return 0; }