*这会调用构造函数?

Kun*_*mar 8 c++

对"this"指针的操作是否会调用构造函数?

我有一个构造函数定义如下

    Cents(int cents)
    {
            cout<<"in cents constructor\n";
            m_cents = cents;
    }

    friend Cents operator + (const Cents &c1, const Cents &c2)
    {           
            return Cents(c1.m_cents + c2.m_cents);
    }

    Cents operator ++ (int)
    {
            cout<<"In c++ function\n";
            Cents c(m_cents);
            *this = *this + 1 ;
            return c;
    }
Run Code Online (Sandbox Code Playgroud)

在主要功能我... ...

    Cents c;
    cout<<"Before post incrementing\n";
    c++; //This part is calling the constructor thrice 
Run Code Online (Sandbox Code Playgroud)

现在,如果我正在做一些像*this = *this + 1.它调用此构造函数两次.

究竟是怎么回事.是否*this创建临时对象并将值分配给原始对象?

Raf*_*cki 11

不,取消引用指针不会创建任何新对象.

Hovever,如果你operator+只为你的类的实例定义,将会有一个新的实例构造 1,因为构造函数Cents(int cents)没有标记为显式.