「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;
}
我也有東西像...
Cents c;
cout<<"Before post incrementing\n";
c++; //This part is calling the constructor thrice
現在,如果我做這樣*this = *this + 1
一些操作。 它調用這個構造函數兩次。
這裏究竟發生了什麼。 *this
是否創建臨時對象並將該值賦給原始對象?
請向我們展示更多代碼。你有複製構造函數和賦值運算符定義? – 2012-04-22 10:36:51
@RafałRawicki....不,我沒有任何複製構造函數或賦值運算符定義。 – 2012-04-22 10:40:32
你能發佈完整的例子嗎?請參閱http://sscce.org我認爲,應該在此表達式中調用一次Cents構造函數,而不是兩次。 – 2012-04-22 10:41:52