我在测试文件中获得了以下代码以实现:
cout << "Testing the Matrix constructors:" << endl;
cout << "Case 1: Creating a 2x4 matrix of zeros with the standard constructor:" << endl;
{
Matrix matrix(2, 4);
cout << matrix << endl;
目前,我在.cpp文件中用于构造函数的代码如下:
Matrix::Matrix (const int noOfRows, const int noOfCols){
double **p_matrix = new double*[noOfRows];
for(int i=0; i< noOfRows; i++){
p_matrix[i] = new double[noOfCols];
}
for(int i=0; i< noOfRows; i++){
for(int j=0; j<noOfCols; j++){
p_matrix[i][j] = 0;
}
}
我主要的困惑是代码的cout <
我认为一种解决方案可能是重载我的<
std::ostream& operator<<(std::ostream& output, const Matrix& rhs){
output << rhs.data << std::endl;
return output; }
我放入rhs.data的原因是因为我尝试了rhs.matrix和rhs.p_matrix,但收到一个错误,指出需要成员变量。在我的.h文件中,仅允许我使用以下成员变量:
int noOfRows:存储行数的成员变量
int noOfColumns:存储列数的成员变量
double * data:将变量存储到按列排列的矩阵条目的1-D数组的地址的成员变量,即第一列后跟第二列,依此类推
向前
int GetIndex(const int rowIdx,const int columnIdx)const:成员
该函数确定在rowIdx指定的行和columnIdx指定的列中,矩阵项沿一维数组(数据)的位置(索引)。
我不确定如何仅使用这些变量来使用运算符重载,所以这是最佳解决方案还是有替代方法?考虑到我无法更改测试文件或4个成员变量的限制
最佳答案
正如你所说:
在我的.h文件中,唯一允许我使用的成员变量是... double * data:将地址存储到矩阵的一维数组的成员变量
因此,Matrix
构造函数应初始化data
属性,而不是局部的double **p_matrix
变量(然后使data
未初始化)...
只需替换:
Matrix::Matrix (const int noOfRows, const int noOfCols)
{
double **p_matrix = new double*[noOfRows];
for(int i=0; i< noOfRows; i++){
p_matrix[i] = new double[noOfCols];
}
for(int i=0; i< noOfRows; i++){
for(int j=0; j<noOfCols; j++){
p_matrix[i][j] = 0;
}
}
}
通过:
1.如果您的
data
属性是double**
Matrix::Matrix (const int noOfRows, const int noOfCols)
{
this->noOfRows = noOfRows;
this->noOfCols = noOfCols;
data = new double*[noOfRows];
for(int i=0; i< noOfRows; i++){
data[i] = new double[noOfCols];
}
for(int i=0; i< noOfRows; i++){
for(int j=0; j<noOfCols; j++){
data[i][j] = 0;
}
}
}
稍后,您可以执行以下操作:
std::ostream& operator<<(std::ostream& output, const Matrix& rhs)
{
for( int i=0; i< noOfRows; i++){
for( int j=0; j < noOfCols; j++){
output << rhs.data[i][j] << " "; // next column
}
output << std::endl; // next line
}
return output;
}
2.如果您的
data
属性是double*
Matrix::Matrix (const int noOfRows, const int noOfCols){
this->noOfRows = noOfRows;
this->noOfCols = noOfCols;
data = new double[noOfRows*noOfCols];
for(int i=0; i< noOfRows*noOfCols; i++){
data[i] = 0;
}
}
稍后,您可以执行以下操作:
std::ostream& operator<<(std::ostream& output, const Matrix& rhs)
{
for( int i=0; i< noOfRows; i++){
for( int j=0; j < noOfCols; j++){
output << rhs.data[noOfCols*i+j] << " "; // next column
}
output << std::endl; // next line
}
return output;
}
在这两种情况下,请确保
data
在头文件中是公用的,或者确保operator<<(std::ostream& output, const Matrix& rhs)
是friend
的Matrix
(或添加吸气剂)。顺便说一下,请注意,矩阵通常存储为
double*
而不是double**
。关于c++ - 如何调用对象/构造函数以返回2D数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34547401/