我已经创建了类和第一个构造函数,但是我不知道如何按照 2 中的要求将 2d 数组初始化为 ref,需要使用动态内存分配来执行此操作。
创建一个名为 matrix 的类,具有跟随的私有(private)成员:
• int **p;
• int 行;
• 整数列;
该类应具有以下成员函数:
我的代码:
class Matrix
{
private:
int **p;
int rows;
int cols;
public:
// CONSTRUCTORS
Matrix()
{
rows = 2;
cols = 2;
p = new int*[2];
// initialize the array with 2x2 size
for (int i=0; i<2; i++)
{
p[i] = new int[2];
}
// taking input for the array
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
p[i][j] = 0;
}
}
};
Matrix(int **ref, int r, int c)
{
rows = r;
cols = c;
p = new int*[rows];
// initialize the array with 2x2 size
for (int i=0; i<rows; i++)
{
p[i] = new int[cols];
}
// taking input for the array
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
p[i][j] = **ref;
}
}
}
friend ostream& operator << (ostream& output, Matrix& obj)
{
output << obj.rows;
cout << " = ROWS" << endl;
output << obj.cols;
cout << " = columns" << endl;
for (int i=0; i<obj.rows; i++)
{
for(int j=0; j<obj.cols;j++)
{
cout << obj.p[i][j] << " " ;
}
cout << endl;
}
return output;
}
};
int main()
{
Matrix a;
cout << a << endl;
return 0;
}
最佳答案
看来p[i][j] = **ref;
应该是 p[i][j] = ref[i][j];
.
你也应该关注 The Rule of Three .换句话说,您应该声明复制构造函数和赋值运算符以正确处理对象(包括指针)复制。
关于c++ - 在 C++ 中初始化动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62819066/