c++ - C++运算符重载失败输出+运算
问题描述
我正在学习 C++ 并尝试为矩阵编写 C++ 类,我将矩阵存储为一维 C 数组。为此,我定义了一个element
成员函数来根据矩阵元素在数组中的位置来访问它们。然后我重载了<<
and+
运算符来处理矩阵的显示和添加。运算符按预期工作,<<
如下例所示:
#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 可能存在问题,但奇怪的是上述解决方法是否有效。
解决方案
您的<<
运算符采用对矩阵的非常量引用作为参数。这意味着它不能引用临时对象。A+B
如果您不将其分配给某物,则结果是一个临时对象。
所以你需要改变这个:
std::ostream & operator<<(std::ostream &os, matrix &M);
进入这个:
std::ostream & operator<<(std::ostream &os, const matrix &M);
您可能迟早会遇到与您的+
-operator 相同的问题:
matrix operator+(matrix &M)
应该
// Both `M` and `*this` should be const
matrix operator+(const matrix &M) const
自然地,您的element
方法会出现问题,该方法只能作用于非常量对象,因此您还需要一个作用于 const 对象的变体:
class matrix
{
....
public:
double & element(int r, int c);
double element(int r, int c) const;
...
}
推荐阅读
- python - 我如何重塑这个 numpy 数组
- xml - 我想通过 xslt 对这个 xml 文件的日期进行排序,但日期不是标准格式
- python - 在python中用正则表达式拆分字符串的某些部分
- java - 有没有办法用 jUnitJupiter 测试列表/集合的顺序?
- arrays - 如何使用映射分配结构类型值?
- sorting - TYPO3 extbase,改变前端元素的排序
- javascript - 这两种时间格式有什么区别以及如何转换
- javascript - JQuery - 从父 div 中获取未知数量的孩子的 id 值
- c# - 错误:已发布代码上的“找不到路径的一部分”
- json - 如何在python中附加一个json文件