实现一个类层次管理整数数组,基类intArray为一维数组,派生类Maxtrix为二维数组,Array3D为三维数组。请参照基类intArray的定义,完成派生类Matrix和Array3D的定义。其中intArray定义如下: class intArray{ public: intArray(int count) { ar=new int[count]; n=count; } int & elem(int i) { return ar[i]; } void print( ) { int i; for(i=0;i<n;i++) cout<<ar[i]<< " "; } protected: int *ar; int n; //代表元素个数 };
时间: 2023-06-19 09:05:49 浏览: 105
c#基础之数组与接口使用示例(遍历数组 二维数组)
以下是Matrix和Array3D的定义:
class Matrix : public intArray {
public:
Matrix(int rowCount, int colCount) : intArray(rowCount * colCount) {
rows = rowCount;
cols = colCount;
}
int& elem(int row, int col) {
return ar[row * cols + col];
}
void print() {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
cout << elem(i, j) << " ";
}
cout << endl;
}
}
private:
int rows, cols;
};
class Array3D : public intArray {
public:
Array3D(int dim1Count, int dim2Count, int dim3Count) : intArray(dim1Count * dim2Count * dim3Count) {
dim1 = dim1Count;
dim2 = dim2Count;
dim3 = dim3Count;
}
int& elem(int dim1Index, int dim2Index, int dim3Index) {
return ar[dim1Index * dim2 * dim3 + dim2Index * dim3 + dim3Index];
}
void print() {
int i, j, k;
for (i = 0; i < dim1; i++) {
for (j = 0; j < dim2; j++) {
for (k = 0; k < dim3; k++) {
cout << elem(i, j, k) << " ";
}
cout << endl;
}
cout << endl;
}
}
private:
int dim1, dim2, dim3;
};
阅读全文