gpt4 book ai didi

C++运算符重载无法输出+运算

转载 作者:行者123 更新时间:2023-12-01 23:27:34 30 4
gpt4 key购买 nike

我正在学习 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 时可能存在问题,但奇怪的是上述变通解决方案是否有效。

最佳答案

你的 <<运算符将对矩阵的非常量引用作为参数。这意味着它不能引用临时对象。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 对象的方法,因此您还需要一个作用于 const 对象的变体:

class matrix
{
....
public:
double & element(int r, int c);
double element(int r, int c) const;
...
}

关于C++运算符重载无法输出+运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66960998/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com