2017-02-23 27 views
0

我是C++新手,雖然之前我曾經使用過C和Java。C++連續檢查對象變量的值會得到不同的結果嗎?

在下面的代碼,我:

  • 定義多邊形類。現在它只有1個變量:爲NumPoints
  • 創建一個全局指針指向一個多邊形對象是空
  • 定義處理程序click事件,而如果對象存在,只是打印爲NumPoints的價值。如果不是這樣,它會創建它並設置爲NumPoints的值爲0

    //defining polygon class 
    class polygon{ 
    public: 
        int numpoints; 
    }; 
    
    //create a global pointer that's uninitialized 
    static polygon *current = NULL; 
    
    //define a click handler. 
    void leftClick(int x, int y){ 
        if (current==NULL){ 
         polygon newpoly; 
         current = &newpoly; 
         current->numpoints = 0; 
         printf("created new polygon\n"); 
         printf("%i points\n", (*current).numpoints); 
    
        }else{ 
    
         printf("polygon exists\n"); 
         printf("%i points\n", (*current).numpoints); 
        } 
    } 
    

第一次點擊後,該程序將打印

created new polygon 
    0 points 

預期。然而,第二次及以後點擊之後,它打印

polygon exists 
    -1567658064 points 

或者其他一些看似隨機數。有人知道這裏發生了什麼?爲什麼價值不停留在0?任何幫助表示讚賞。

回答

0

這應該工作:

//defining polygon class 
class polygon{ 
public: 
    int numpoints; 
}; 

//create a global pointer that's uninitialized 
static polygon *current = NULL; 
polygon newpoly;  
//define a click handler. 
void leftClick(int x, int y){ 
    if (current==NULL){ 

     current = &newpoly; 
     current->numpoints = 0; 
     printf("created new polygon\n"); 
     printf("%i points\n", (*current).numpoints); 

    }else{ 

     printf("polygon exists\n"); 
     printf("%i points\n", (*current).numpoints); 
    } 
} 

的問題是,newpoly是第一printf後,因爲它超出範圍破壞。你必須學習如何在C++中管理內存。

0

newpoly是一個局部變量。你正在接受它的地址,但之後它會被銷燬,這樣地址就不會再發生變化了。

你可以做的是使用動態分配代替:current = new polygon;


但是,如果沒有以某種方式包裝它,使用動態分配通常是不好的。

如果您使用的是C++ 11,則可以使用標頭<memory>中的std::unique_ptr<polygon>

結果是

static std::unique_ptr<polygon> current; // No need to set it to NULL 
... 
current.reset(new polygon); 

這樣的變化將確保在需要的時候你的配置是正確delete d。

+0

這是非常糟糕的建議。創建浮動和非託管指針不是正確的解決方案。 –

+0

這是一個可行的解決方案,儘管它不是理想的 – Telokis

+0

在給初學者提供建議時我會小心謹慎。你應該針對提供好的建議,而不是僅僅讓有用的東西。至少提到這是一個不好的解決方案,因爲這個和那個,一個好的解決方案是這樣。在你的情況下,如果你想提一個好的解決方案,建議把它包裝在一個類中,並讓析構函數來處理刪除操作,或者在類中使用智能指針。 –

相關問題