首页 > 解决方案 > 二进制表达式的无效操作数(同时使用两个重载运算符时)

问题描述

我收到以下错误:error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Matrix') 相关代码如下:

Matrix Matrix::operator+(const Matrix &b){
    Matrix C(r,c);
    int i,j;
    if(b.r!=r||b.c!=c)
        printf("invalid operation!");
    else {for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            C.data[i][j]=data[i][j]+b.data[i][j];
        }
        cout<<endl;
    }
    }
    return C;
}
ostream & operator<<(ostream &out, Matrix &A){
    int i,j;
    for(i=0;i<A.r;i++)
    {
        for(j=0;j<A.c;j++)
        {
            out<<setw(6)<<A.data[i][j];
        }
        cout<<endl;
    }
    return out;
}

&

    cout<<"A + B:"<<endl;
    cout << (A + B) <<endl;

但是在我把第二部分改成这个之后,一切顺利:

    Matrix C;
    cout<<"A + B:"<<endl;
    cout << C <<endl;

我真的很困惑原始代码有什么问题……实际上它是我编程作业的固定框架的一部分,我不允许更改它。问答

标签: c++

解决方案


(A + B)

此加法运算的结果是一个临时值。

ostream & operator<<(ostream &out, Matrix &A){

临时对象不绑定或转换为可变引用。C++ 不能以这种方式工作。它们只绑定到const引用。operator<<只需将此重载的第二个参数更改const Matrix &为 ,并根据需要对此重载的内容进行任何适当的更改(可能还需要更改Matrix's 神秘的“数据”成员的operator[]重载,因为它现在在const类上被调用实例)。


推荐阅读