Strange behavior when writing C ++ codes with decrement operator

I am starting C ++, I come across strange code while coding, below is the problem.

 class INT
{
    friend ostream& operator<<(ostream& os, const INT &i);

public:
    INT(int i) :m_i(i){};
    INT(const INT& i)
    {
        m_i = i.m_i;
    }
    INT& operator++()
    {
        ++(this->m_i);
        return  *this;
    }
    const INT operator++(int)
    {
        INT temp = *this;
        ++(*this);
        return temp;
    }
    INT& operator--()
    {
        --(this->m_i);
        return  *this;
    }
    const INT& operator--(int)
    {
        INT temp = *this;
        --(*this);
        return temp;
    }
    int& operator*() const
    {
        return (int&)m_i;
    }
private:
    int m_i;
};

ostream& operator<<(ostream& os, const INT &i)
{
    os << "[" <<i.m_i<< "]";
    return os;
}

int main(int argc, char* argv[])
{
    INT i(5);
    cout << i++;
    cout << ++i;
    cout << (i--);
    cout << --i;
    cout << *i;
}

      

I get the result

[5][7][-858993460][5]5

      

my expected result

[5][7][7][5]5

      

I am using Visual Studio 2013. Thanks a lot!

+3


source to share


1 answer


const INT& operator--(int) { ... }

      

wrong. You are returning a reference to an object in the function scope. This link becomes invalid after the function returns. Change it to:

INT operator--(int) { ... }

      

While on it you don't need const

to:



const INT operator++(int) { ... }

      

Change it to:

INT operator++(int) { ... }

      

+6


source







All Articles