gpt4 book ai didi

c++ - 二进制表达式的无效操作数(同时使用两个重载运算符时)

转载 作者:行者123 更新时间:2023-12-01 14:52:40 25 4
gpt4 key购买 nike

我收到以下错误: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;

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

最佳答案

(A + B)

此加法运算的结果是一个临时值。
ostream & operator<<(ostream &out, Matrix &A){

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

关于c++ - 二进制表达式的无效操作数(同时使用两个重载运算符时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61925722/

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