Problem with chaining operator<< and operator++

后端 未结 2 700
耶瑟儿~
耶瑟儿~ 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:54

    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<

    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<

提交回复
热议问题