简体   繁体   中英

My pre increment is working fine but not the post increment

I have implemented the following class and tried to overload the pre and post-increment operator along with the extraction '>>' operator. The programs runs fine till 'cout << ++num1;' but prints junk values for the last line 'cout << num1++;'. I cannot figure out that why is it working fine for pre-increment but not for post-increment.

class ComplexNumber
{
private:
    float real;
    float img;
public:
    ComplexNumber();
    ComplexNumber(float, float);
    ComplexNumber(const ComplexNumber& cn);
    friend istream& operator>>(istream& in, ComplexNumber& cn);
    // cin >> complexNo1 >> complexNo2;
    friend ostream& operator<<(ostream& out, const ComplexNumber& cn);
    //cout << complexNo1 << complexNo2; //3+4i, 5+10i
    ComplexNumber& operator++(int);
    //post increment operator. complexNo++;
    ComplexNumber& operator++();
    //pre increment operator. ++complexNo;
ComplexNumber& ComplexNumber::operator++(int x) // postincrement
{
    ComplexNumber c = *this;
    ++(*this);
    return c;
}
ComplexNumber& ComplexNumber::operator++() // preincrement
{
    real++;
    img++;
    return *this;
}
int main()
{
    ComplexNumber num1;//,num2,num3
    cin >> num1;
    cout << "-------------------------------------------" << endl;
    cout << "Complex Number is : ";
    cout << num1;
    cout << ++num1;
    cout << num1++;
}

Your post-increment operator is returning reference to local object, which will be destroyed when function ends, the returned reference is always dangling and dereference on it leads to UB.

Post-increment operator is supposed to return-by-value, eg

ComplexNumber ComplexNumber::operator++(int x) // postincrement
{
    ComplexNumber c = *this;
    ++(*this);
    return c;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM