正确覆盖<<<<<<<< cout的运营商?

时间:2017-11-22 23:21:13

标签: c++ c++11 reference operator-overloading friend

friend ostream& operator<<(ostream&, currency&);

这是覆盖&lt;&lt;的声明操作

currency multiply(const double) const;

这是乘法方法的声明。

当我想使用cout输出a.multiply(2)

编译器告诉我invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'currency')

有谁能告诉我这个覆盖功能是如何工作的以及如何解决它?

谢谢!

1 个答案:

答案 0 :(得分:1)

此运算符

currency multiply(const double) const;
^^^^^^^^

创建货币类型的临时对象。虽然这个运算符

friend ostream& operator<<(ostream&, currency&);
                                     ^^^^^^^^^  

期望非常量引用。您不能使用非常量引用绑定临时对象。

将运算符声明为

friend ostream& operator<<(ostream&, const currency&);
                                     ^^^^^

或者如果操作员更改了对象,则使用右值参考

再添加一个运算符
friend ostream& operator<<(ostream&, currency&&);
                                     ^^^^^^^^^^^ 
相关问题