[英]no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}'
Learning C++ right now and ran into a bit of a problem. 现在学习C ++并遇到了一些问题。 While trying to complete an example and make sure it works ran into the error:
在尝试完成示例并确保其正常工作时遇到了错误:
error: no match for 'operator<<' (operand types are 'std::istream' and 'const int') and Complex
. 错误:
no match for 'operator<<' (operand types are 'std::istream' and 'const int') and Complex
。 Here is my code. 这是我的代码。
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
int getR() const { return real; }
int getC() const { return imag ; }
ostream& aff(ostream& out)
{
out << real << " + i" << imag ;
return out ;
}
void print() { cout << real << " + i" << imag << endl; }
};
Complex operator + (const Complex & a , const Complex &b )
{
int r = a.getR() + b.getR();
int c = a.getC() + b.getC();
Complex x(r , c);
return x ;
}
ostream& operator<<(ostream& out , Complex& c)
{
return c.aff(out) ;
}
int main()
{
Complex c1(10, 5), c2(2, 4);
cout << c1 + c2 << endl ; // An example call to "operator+"
}
Not sure what is wrong with my code, can anyone help? 不确定我的代码有什么问题,有人可以帮忙吗?
operator +
returns by-value, that means what it returns is a temporary, it can't be bound to lvalue-reference to non-const (ie Complex&
), which is the parameter type of operator<<
. operator +
返回按值,这意味着它返回的是临时值,它不能绑定到非常量的左值引用(即Complex&
),这是operator<<
的参数类型。
You can change the parameter type to const Complex&
, 您可以将参数类型更改为
const Complex&
,
ostream& operator<<(ostream& out , const Complex& c)
// ~~~~~
{
return c.aff(out) ;
}
and you have to make aff
a const
member function, to make it possible to be called on a const
object. 并且必须使
aff
成为const
成员函数,以便可以在const
对象上调用它。
ostream& aff(ostream& out) const
// ~~~~~
{
out << real << " + i" << imag ;
return out ;
}
Your function is waiting for a lvalue reference, and you try to print c1 + c2
that is a temporary. 您的函数正在等待左值引用,然后尝试打印临时的
c1 + c2
。
You can bind a temporary to a const lvalue reference, so you must wait for a const Complex &c
您可以将临时绑定到const左值引用,因此必须等待
const Complex &c
ostream& operator<<(ostream& out , const Complex& c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.