Operator overloading "float" and "<<"
This question already has an answer here:
Your output operator<<
should accept the stream as the first argument, and the fraction as the second argument. Right now, it does the opposite (the fraction is the first argument, and the stream is the second). This means the operator isn't called, instead the fraction is converted to float
and then the float is displayed.
The operator you wrote can be called with a << cout
, which is obviously wrong.
Instead of making it the member operator, you should implement this operator as (friend) non-member, outside of your class.
Sample signature:
std::ostream& operator<<(std::ostream& os, const Fraction& f);
Implement operator <<
outside of your class, as a non-member (friend) function.
See Operator overloading.
operator<<
不应该是类的成员,因为它需要将流对象作为其第一个参数,并具有签名ostream &operator<<(ostream &, Fraction)
。
上一篇: C ++
下一篇: 运算符重载“float”和“<<”