为什么重载“ <<”需要const参数?

时间:2019-04-29 16:01:56

标签: c++

我上课

class complex
{
 [...]
 complex operator+(const complex &c) const;
 [...]
 friend std::ostream &operator<<(std::ostream &os, const complex &c);
};
complex complex::operator+(const complex &c) const
{
 complex result;
 result.real_m = real_m + c.real_m;
 result.imaginary_m = imaginary_m + c.imaginary_m;
 return result;
}
std::ostream &operator<<(std::ostream &os, const complex &c)
{
 os << "(" << c.real_m << "," << c.imaginary_m << "i)";
 return os;
}
int main()
{
  complex a(3.0, 4.0);
  complex c(5.0, 8.0);
  cout << "a is " << a << '\n';
  cout << "a + c is " << a + c << '\n';
  [...]
 }

并且,一切正常,但如果我在const中删除std::ostream &operator<<(std::ostream &os, const complex &c),则cout << "a is " << a << '\n';正常,但cout << "a + c is " << a + c << '\n';却无效,它说:没有运算符“ <<匹配这些操作数。因此,为什么在没有const的情况下不起作用?

1 个答案:

答案 0 :(得分:1)

a + c不是左值,因此不能在其上使用非常量引用。