【发布时间】:2021-07-01 18:51:38
【问题描述】:
我正在学习 C++ 并尝试为矩阵编写 C++ 类,我将矩阵存储为一维 C 数组。为此,我定义了一个element 成员函数来根据矩阵元素在数组中的位置来访问它们。然后我重载了<< 和+ 运算符来处理矩阵的显示和添加。 << 运算符按预期工作,如下例所示:
#include<iostream>
class matrix {
friend std::ostream & operator<<(std::ostream &os, matrix &M);
private:
int rows{}, columns{};
double *array {nullptr};
public:
matrix(int rows, int columns);
~matrix() {}
double & element(int r, int c);
matrix operator+(matrix &M)
{
matrix N(rows, columns);
if (M.rows!=rows || M.columns!=columns){
std::cout << "ERROR: DIMENSIONS OF MATRICES DO NOT MATCH" << std::endl;
}
else{
for (int i{1}; i<=M.rows; i++)
for (int j{1}; j<=M.columns; j++){
N.element(i,j) = element(i,j) + M.element(i,j);
}
}
return N;
}
};
matrix::matrix(int r, int c)
{
rows = r;
columns = c;
array = new double[rows*columns];
for(int i{0}; i<rows*columns; i++) array[i]=0.0;
}
double & matrix::element(int i, int j)
{
int loc{0};
loc = (j-1) + (i-1)*columns;
return array[loc];
}
std::ostream & operator<<(std::ostream &os, matrix &M)
{
for (int i{1}; i<=M.rows; i++){
os << "[ ";
for (int j{1}; j<=M.columns; j++){
os << M.element(i,j) << " ";
}
os << "] \n";
}
return os;
}
int main() {
matrix A(2,2);
matrix B(2,2);
A.element(1,1) = 1;
A.element(1,2) = 2;
A.element(2,1) = 3;
A.element(2,2) = 4;
B.element(1,1) = 1;
B.element(1,2) = 2;
B.element(2,1) = 3;
B.element(2,2) = 4;
std::cout << A << std::endl;
std::cout << B << std::endl;
return 0;
}
然后我无法显示两个矩阵的相加:
std::cout << A+B << std::endl;
但是,如果我在显示它们的总和之前分解运算并分别添加矩阵,我会得到正确的输出,这让我相信 + 运算符也可以正常工作:
matrix C(2,2);
C = A+B;
std::cout << C << std::endl;
该错误似乎表明将矩阵元素转换为 ostream 可能存在问题,但奇怪的是上述解决方法是否有效。
【问题讨论】:
-
对您的代码的注释,与您的问题无关:为
array使用智能指针,那么您不需要析构函数。不要使用new/delete,除非你想了解c++的内部工作原理。真的很容易把事情搞砸。
标签: c++ class matrix operator-overloading ostream