链运算符<<和运算符++ [英] Problem with chaining operator<< and operator++

查看:191
本文介绍了链运算符<<和运算符++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++,但遇到了这个问题:

I'm learning C++ and I have this problem:

#include <iostream>
using namespace std;


class test
{
    public:
    test(){};
    test(int i):var{i}{};

    test& operator++(){++var; return this;}  
    test  operator++(int dummy){test tmp =*this;var++;return tmp;}

    friend ostream& operator<<(ostream&, const test&);


   private:
   int var;
};

ostream& operator<<(ostream& o, const test& obj)
{
    o<<obj.var;
    return o;
}


int main()
{
    test obj{2};
    cout << obj << endl;
    obj++;
    cout << obj << endl;
    cout << obj <<' '<< ++obj<<endl;

    return 0;
}

我期望的输出是: 2个 3 3 4

the output i expected was: 2 3 3 4

相反,我有: 2个 3 4 4

instead i have: 2 3 4 4

如果我用obj ++替换最后一个增量++ obj,情况将更加奇怪: 2个 3 4 3

if i replace the last increment ++obj with obj++ the situation is even more weird: 2 3 4 3

这就像以相反的方式读取流,您能帮我吗?

it's like the stream is read in the opposite way, can you help me?

推荐答案

让我们检查一下线路

cout << obj << ' ' << ++obj << endl;

已翻译.

第1步.

cout << obj

成为

// A non-member function.
operator<<(cout, obj)

第2步.

operator<<(cout, obj) << ' '

成为

// Also a non-member function.
operator<<(operator<<(cout, obj), ' ')

第3步.

operator<<(operator<<(cout, obj), ' ') << ++obj

成为

// Also a non-member function.
operator<<(operator<<(operator<<(cout, obj), ' '), ++obj)

第4步.

operator<<(operator<<(operator<<(cout, obj), ' '), ++obj) << endl;

成为

// A member function.
operator<<(operator<<(operator<<(cout, obj), ' '), ++obj).operator<<(endl);

那是整行.

在这样的表达式中,不能保证operator<<(cout, obj)将在++obj之前执行.看来在您的平台中,在执行operator<<(cout, obj)之前先执行++obj.这就解释了这种行为.

In such an expression there is no guarantee that operator<<(cout, obj) will be executed before ++obj. It appears that in your platform, ++obj is executed before operator<<(cout, obj) is executed. That explains the behavior.

请注意,标准已更改.如果您能够使用C ++ 17,则将获得预期的行为.

Please note that the standard has changed. If you are able to use C++17, you will get the expected behavior.

这篇关于链运算符&lt;&lt;和运算符++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆