简体   繁体   English

Ostream <<和运算符-=用于类吗?

[英]Ostream << and operator -= for classes?

I have 2 classes S and M . 我有2个班级SM When I try to use 当我尝试使用

cout << s3 -= m2;

I get an error that sates: 我收到一条错误消息:

no operator "-=" matches these operands operand types are: std::ostream -= 没有运算符“-=”匹配这些操作数,操作数类型为:std :: ostream-=

class S
{ 
public:
    S& operator-=(M& m)
    {
        //my code
        return *this;
    }
}

I tried with 3 parameters, including ostream , but -= has only 2. How can I fix this? 我尝试使用3个参数,包括ostream ,但是-=只有2个。我该如何解决?

This has to do with operator precedence . 这与运算符优先级有关 << has a higher precedence than -= so <<的优先级比-=因此

cout<<s3-=m2;

is treated as 被视为

(cout << s3) -= m2;

and not 并不是

cout << (s3 -= m2);

You need to use the above form to get what you want. 您需要使用上面的表格来获取想要的东西。

You have no way to fix this. 您无法解决此问题。 The operator precedence rules in c++ are fixed and cannot be overloaded. c++中的运算符优先级规则是固定的,不能重载。

The only possible solution is to change the using code. 唯一可能的解决方案是更改使用代码。 For example, if you write 例如,如果您写

cout << (s3 -= m2);

then your original code should work. 那么您的原始代码应该可以正常工作。 Another option is splitting the line in two: 另一个选择是将行分为两部分:

s3 -= m2;
cout << s3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM