C++ 为什么超载<<&引用;需要常量参数吗?

C++ 为什么超载<<&引用;需要常量参数吗?,c++,C++,我有一节课 class complex { [...] complex operator+(const complex &c) const; [...] friend std::ostream &operator<<(std::ostream &os, const complex &c); }; 类复合体 { [...] 复数运算符+(const complex&c)const; [...] friend std::ostream&opera

我有一节课

class complex
{
 [...]
 complex operator+(const complex &c) const;
 [...]
 friend std::ostream &operator<<(std::ostream &os, const complex &c);
};
类复合体
{
[...]
复数运算符+(const complex&c)const;
[...]

friend std::ostream&operator
a+c
不是l值,因此不能对其使用非常量引用。

要添加到dupe中:
a+c
创建一个临时对象。
a+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';
  [...]
 }