Problem with chaining operator<< and operator++

穿精又带淫゛_ 提交于 2019-12-02 06:19:39
R Sahu

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.

For starters the data member i can be uninitialized if the default constructor will be used.

Either declare the data member like

int var = 0;

Or redefine the default constructor for example by using the delegating constructor.

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

The pre-increment operator should look like

test& operator++(){++var; return *this;}
                                 ^^^^^

In the post-increment operator the identifier dummy is not used. So remove it

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

This statement

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

has undefined behavior because reading writing the object obj are not sequenced.

You have to split this statement into two statements

cout << obj <<' ';
cout << ++obj<<endl;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!