c++ - 二进制表达式的无效操作数(同时使用两个重载运算符时)
问题描述
我收到以下错误: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){
临时对象不绑定或转换为可变引用。C++ 不能以这种方式工作。它们只绑定到const
引用。operator<<
只需将此重载的第二个参数更改const Matrix &
为 ,并根据需要对此重载的内容进行任何适当的更改(可能还需要更改Matrix
's 神秘的“数据”成员的operator[]
重载,因为它现在在const
类上被调用实例)。
推荐阅读
- ffmpeg - 如何在拍摄/保存时将图像转换为视频,而不是按名称?
- sql-server - 在 vs2017-win2016 托管代理上使用 SQL Server docker 容器
- javascript - 如何用动漫js而不是css动画动画句子?
- firefox - Highcharts Firefox 问题
- excel - 调用 Comment.Replies 属性 (Word) 来自定义 CopyCommentsToExcel()
- c# - 为整个项目禁用 (JetBrains) 代码检查
- ios - 如何在 MacOS 外接显示器插件时获得通知
- python - 如何在 python 光束中制作通用 Protobuf Parser DoFn?
- email - 如何找出您正在使用的 SMTP 端口?
- ios - 表格视图中的单元格没有响应