2013-04-24 62 views
0

我是新來的C + +,我想了解靜態關鍵字的不同用途,我讀其中之一是定義一個靜態變量類並使用範圍運算符調用它。我試圖用它,但Visual Studio 2012產生鏈接錯誤。我的代碼是:C++靜態變量產生致命錯誤LNK1120:1在Visual Studio中無法解析的外部

class Vehicle 
{ 
public: 
    Vehicle(){}; 
    ~Vehicle(){}; 
    static int temp; 
}; 

int _tmain(int argc, _TCHAR* argv[]) 
{ 

    Vehicle::temp=100; 

    std::cout << Vehicle::temp << std::endl; 

    system("Pause"); 
    return 0; 
} 

和錯誤是:

1> LearningC++ OBJ:錯誤LNK2001:無法解析的外部符號 「公用:靜態INT車輛::溫度」?(溫度@車輛@@ 2HA)

1> C:\用戶\ AVRAAM \文件\視覺工作室2012 \項目\ LearningC++ \調試\ LearningC++ EXE:致命錯誤LNK1120:1周無法解析的外部

什麼可以CAUS這個問題?

EDIT1(以使其更清晰):

我的問題是如何能夠訪問類中聲明的靜態變量?這可能沒有使用成員函數?

+1

您需要定義變量。在類定義之後添加'int Vehicle :: temp;'。 – jrok 2013-04-24 19:02:51

回答

2

您需要定義tempclass Vechicle後補充一點:

class Vehicle 
{ 
// Left out class code for brevity 
    void useTemp() { temp = 200 ; } // Adding method inside class the uses temp 
}; 

int Vehicle::temp = 0 ; 

注意,你不需要static關鍵字時,您定義temp。既然是static你不需要的類的實例來訪問變量,讓你在main有代碼是正確的:

Vehicle::temp=100; 

std::cout << Vehicle::temp << std::endl; 

Vehicle v1 ; 
v1.useTemp() ; 

std::cout << Vehicle::temp << std::endl; 
+0

@AvraamMavridis我添加了一些更多的細節,希望能夠清楚地說明如何在課堂內外使用'temp'。 – 2013-04-24 19:20:40

0

您需要定義類的外部static成員:

#include <iostream> 

class Vehicle 
{ 
    public: 
    Vehicle(){}; 
    ~Vehicle(){}; 
    static int temp; 
}; 

int Vehicle::temp = 0; 

int _tmain(int argc, TCHAR* argv[]) 
{ 
    Vehicle::temp = 100; //^^access the variable with classname plus :: 
    std::cout << Vehicle::temp << std::endl; 
    std::cin.get(); 
    return 0; 
} 

然後通過main訪問它,其中類名後跟::和變量名。

+0

你還需要初始化它...... – 2013-04-24 19:32:10

+0

@MehdiKaramosly你是什麼意思?我在主內部給它賦值。在課堂外定義它時可以不給出初始值。 – taocp 2013-04-24 19:34:26

+0

現在看起來好多了,如果你沒有在外面初始化它,然後誤用它,你會得到一個隨機值。 (存儲器中的值),所以在外部初始化它是明智的。 – 2013-04-24 19:36:51

相關問題