Problem with chaining operator<< and operator++

后端 未结 2 705
耶瑟儿~
耶瑟儿~ 2021-01-25 20:22

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

#include 
using namespace std;


class test
{
    public:
             


        
2条回答
  •  故里飘歌
    2021-01-25 20:53

    Let's examine how the line

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

    is translated.

    Step 1.

    cout << obj
    

    becomes

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

    Step 2.

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

    becomes

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

    Step 3.

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

    becomes

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

    Step 4.

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

    becomes

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

    That's the entire line.

    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.

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

提交回复
热议问题