2012-10-31 37 views
0

我在3個文件以下代碼:C++ const的難題

Defines.h

#ifndef Defines_h 
extern const unsigned int SIZE; 

#endif 

Defines.cpp

#include "Defines.h" 

const unsigned int SIZE = 10; 

Main.cpp的

#include "Defines.h" 

int main() 
{ 
    int x[SIZE] = {0}; 
} 

在編譯我會在數組定義行錯誤:

錯誤C2057:預期的常量表達式和 C2466:不能分配常量大小的數組0

爲什麼會發生這種情況,畢竟我有SIZE這確實是一個常數?

+2

我不認爲你可以這樣做。數組的大小需要在編譯時知道,但它是鏈接器找到定義。 – chris

+0

你試圖初始化數組的所有元素爲0嗎? –

+0

@BenGlasser,這就是它的樣子。 – chris

回答

2

const unsigned int SIZE = 10;移入標題並刪除extern行。通過一個簡單的const int值,直接在頭文件中聲明它是安全無害的。

0

const隱含爲static,即使在SIZE定義中也需要extern。包含文件將不會鏈接,因爲它正在尋找具有外部鏈接的const unsigned int SIZE

+0

_「包含文件將不會鏈接,因爲它正在尋找一個'const unsigned int SIZE'外部聯繫「。在這個陳述中,幾乎所有可能出錯的東西都是錯誤的。 – jogojapan