c++风格,如何在类定义一个二维数组。
如何采用c++的语言风格,在类中定义一个私有的二维数组,并通过构造函数为其赋值
class MyClass {
private:
int myArray[3][4]; // 定义一个3行4列的二维数组作为私有成员变量
public:
MyClass() { // 构造函数
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
myArray[i][j] = i * j; // 为二维数组赋值
}
}
}
};
回答:
要在C++类中定义一个私有的二维数组,并通过构造函数为其赋值,可以按照以下步骤来实现:
示例使用数组指针的方式:
class MyClass {
private:
int** matrix; // 二维数组指针
int rows; // 二维数组的行数
int cols; // 二维数组的列数
public:
MyClass(int rows, int cols) {
this->rows = rows;
this->cols = cols;
// 动态分配二维数组内存空间
matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// 调用构造函数给二维数组赋值,默认为0
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
~MyClass() {
// 释放二维数组内存空间
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
};
示例使用vector嵌套的方式:
class MyClass {
private:
std::vector<std::vector<int>> matrix; // 嵌套vector实现二维数组
public:
MyClass(int rows, int cols) {
// 调整vector大小并初始化为0
matrix.resize(rows, std::vector<int>(cols, 0));
}
};
示例中使用参数列表传递二维数组的方式:
class MyClass {
private:
int** matrix;
int rows;
int cols;
public:
MyClass(int rows, int cols, int** data) {
this->rows = rows;
this->cols = cols;
// 动态分配二维数组内存空间
matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// 将传递的二维数组的值赋给私有的二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = data[i][j];
}
}
}
~MyClass() {
// 释放二维数组内存空间
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
};
使用示例:
int main() {
int rows = 3;
int cols = 4;
// 创建二维数组并赋值
int** data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
for (int j = 0; j < cols; j++) {
data[i][j] = i * cols + j;
}
}
// 创建MyClass对象,传递二维数组并赋值
MyClass obj(rows, cols, data);
// 释放二维数组内存空间
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
return 0;
}
以上是使用C++语言风格在类中定义一个私有的二维数组的解决方案,其中包含了使用数组指针和vector嵌套两种实现方式,并通过构造函数给二维数组赋初值的示例代码。