【发布时间】:2016-04-05 11:35:53
【问题描述】:
我的测试文件中给出了以下代码来实现:
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:将地址存储到按列排列的矩阵条目的一维数组的成员变量,即第一列后跟第二列,依此类推 第四
- int GetIndex (const int rowIdx, const int columnIdx) const: 成员 确定由 rowIdx 指定的行和由 columnIdx 指定的列中的矩阵条目沿一维数组(数据)的位置(索引)的函数。
我不确定如何仅使用这些变量来使用运算符重载,所以这是最佳解决方案还是有替代方法?考虑到我无法更改测试文件或 4 个成员变量的限制
【问题讨论】:
标签: c++ arrays constructor operator-overloading