C++ 在c+中初始化动态二维数组+;
我已经创建了类和第一个构造函数,但我不知道如何按照第2部分的要求将2d数组初始化为ref,需要使用动态内存分配来完成这项工作 创建名为matrix的类,该类包含以下私有成员: •int**p •整数行 •int cols 该类应具有以下成员函数:C++ 在c+中初始化动态二维数组+;,c++,arrays,dynamic,2d,C++,Arrays,Dynamic,2d,我已经创建了类和第一个构造函数,但我不知道如何按照第2部分的要求将2d数组初始化为ref,需要使用动态内存分配来完成这项工作 创建名为matrix的类,该类包含以下私有成员: •int**p •整数行 •int cols 该类应具有以下成员函数: 矩阵()将2d数组初始化为零。假设行=2,列=2 矩阵(int**ref,int r,int c)将2d数组初始化为ref 我的代码: class 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;
}
类矩阵
{
私人:
int**p;
int行;
int cols;
公众:
//建设者
矩阵()
{
行数=2;
cols=2;
p=新整数*[2];
//使用2x2大小初始化阵列
对于(inti=0;i来说,p[i][j]=**ref;
应该是p[i][j]=ref[i][j];
你也应该遵循。换句话说,你应该声明复制构造函数和赋值操作符来正确处理对象(包括指针)的复制。我如何在主函数中调用它?它将像int data[2][3]={{1,2,3},{4,5,6};int*p[]={data[0],data[1]};矩阵a(p,2,3)
令人失望的是,他们没有使用size\u t
而不是int
来指定行
和列
。也许他们想要两者都是负数?