首页 > 解决方案 > 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 可能存在问题,但奇怪的是上述解决方法是否有效。

标签: c++classmatrixoperator-overloadingostream

解决方案


您的<<运算符采用对矩阵的非常量引用作为参数。这意味着它不能引用临时对象。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;
   ...
}

推荐阅读