我上课了
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';
没有,它说:没有运算符“<
a + c
不是l值,因此你不能在它上面使用非const引用。