2015-04-21 165 views
0

該程序給出了正確的輸出,但我無法理解。在聲明對象時調用的默認構造函數是如何的?調用默認構造函數

#include <iostream> 
using namespace std; 
class GuessMe { 
private: 
    int *p; 
public: 
    GuessMe(int x=0) 
    { 
     p = new int; 
    } 
    int GetX() 
    { 
     return *p; 
    } 
    void SetX(int x) 
    { 
     *p = x; 
    } 
    ~GuessMe() 
    { 
     delete p; 
    } 
}; 

int main() { 
    GuessMe g1; 
    g1.SetX(10); 
    GuessMe g2(g1); 
    cout << g2.GetX() << endl; 
    return 0; 
} 
+0

你說得對。代碼錯了。你必須在那裏顯式地使默認的構造函數。 –

+0

但它給出了正確的輸出 –

+0

有趣的然後 –

回答

5

這個構造函數有一個默認參數:

GuessMe(int x=0) 

這意味着,當GuessMe是默認構造的,這是因爲如果它被稱爲與價值0參數。請注意,構造函數參數不用於代碼中的任何內容。還要注意的是p被設置爲指向這裏未初始化的整數

p = new int; 

所以調用SetX()會產生未定義行爲之前調用GetX()。推測您要使用的x值設置p

GuessMe(int x=0) 
{ 
    p = new int(x); 
} 

,或者使用初始化而不是分配,

GuessMe(int x=0) : p(new int(x)) 
{ 
} 

此外,閱讀了關於the rule of three,以避免重複刪除。然後學習如何在沒有原始指針的情況下編寫動態分配的對象。