2017-07-18 58 views
2

我有一個global.h看起來像:如何初始化的extern變量命名空間中的

#pragma once 

#include <memory> 

namespace qe 
{ 

    class SubSystemA; 
    class SubSystemB; 
    class SubSystemC; 

    namespace Systems 
    { 

     extern std::unique_ptr<SubSystemA> gSubSystemA; 
     extern std::unique_ptr<SubSystemB> gSubSystemB; 
     extern std::unique_ptr<SubSystemC> gSubSystemC; 

    } 

} 

現在我不知道如果我能在我的main.cpp初始化,但瓦特/電子我在做,它不工作...請諮詢。以下是主要的樣子:

#include "SubSystemA.h" 
#include "SubSystemB.h" 
#include "SubSystemC.h" 
#include "global.h" 

int main() 
{ 

    extern std::unique_ptr<qe::SubSystemA> qe::Systems::gSubSystemA; 
    extern std::unique_ptr<qe::SubSystemB> qe::Systems::gSubSystemB; 
    extern std::unique_ptr<qe::SubSystemC> qe::Systems::gSubSystemC; 

    qe::Systems::gSubSystemA = std::make_unique<qe::SubSystemA>(); 
    qe::Systems::gSubSystemB = std::make_unique<qe::SubSystemB>(); 
    qe::Systems::gSubSystemC = std::make_unique<qe::SubSystemC>(); 

    return 0; 
} 

基本上,我得到「無法解析的外部符號」錯誤,我不知道如何解決它。任何幫助表示感謝,謝謝!

編輯:雖然解決這個問題很高興知道,但對此的備選建議值得歡迎。我只是想輕鬆(並不意味着全球化,但我不介意)訪問像對象這樣的子系統。

+0

在CPP文件中刪除了'extern'聲明;你已經'#include「global.h」''了。將這些項目的定義添加到您的.cpp文件之一。您可以對定義使用初始化器,也可以像當前一樣使用賦值語句。 –

+0

刪除使得它重新定義編譯錯誤。刪除整行(3 unique_ptr <>)仍然給我鏈接器錯誤編譯罰款。 – ChaoSXDemon

回答

3

您應該從main()(即在命名空間範圍內)中定義(初始化)它們,並且不要使用extern說明符,該說明符表示聲明。例如

std::unique_ptr<qe::SubSystemA> qe::Systems::gSubSystemA = std::make_unique<qe::SubSystemA>(); 
std::unique_ptr<qe::SubSystemB> qe::Systems::gSubSystemB = std::make_unique<qe::SubSystemB>(); 
std::unique_ptr<qe::SubSystemC> qe::Systems::gSubSystemC = std::make_unique<qe::SubSystemC>(); 

int main() 
{ 
    ... 
} 
+0

如果它們是依賴訂單的呢?假設我想要B,A,然後按順序C。我認爲C++ 11和以後應該按照你輸入的順序初始化它們......但是我想確認一下。 – ChaoSXDemon

+0

@ChaoSXDemon在單個翻譯單元中,這些變量的初始化總是按照其定義出現在源代碼中的順序排列。不同翻譯單元的變量初始化順序是不確定的。 – songyuanyao

3

線條

qe::Systems::gSubSystemA = std::make_unique<qe::SubSystemA>(); 
qe::Systems::gSubSystemB = std::make_unique<qe::SubSystemB>(); 
qe::Systems::gSubSystemC = std::make_unique<qe::SubSystemC>(); 

main沒有定義的變量。他們給變量賦值。他們需要在所有功能之外進行定義。最好將它們定義在.cpp文件中,該文件對應於聲明它們的.h文件。在你的情況下,該文件應該是global.cpp。在所有名稱空間外添加以下行。

qe::Systems::gSubSystemA = std::make_unique<qe::SubSystemA>(); 
qe::Systems::gSubSystemB = std::make_unique<qe::SubSystemB>(); 
qe::Systems::gSubSystemC = std::make_unique<qe::SubSystemC>(); 

您還可以使用:

namespace qe 
{ 
    namespace Systems 
    { 
     gSubSystemA = std::make_unique<SubSystemA>(); 
     gSubSystemB = std::make_unique<SubSystemB>(); 
     gSubSystemC = std::make_unique<SubSystemC>(); 
    } 
} 
+0

如果我在global.h文件中初始化它們,我需要包含所有這些標題,我想避免這種情況,但是謝謝你的建議。 – ChaoSXDemon

+0

@ChaoSXDemon,也許你誤解了。您可以在.cpp文件中定義和初始化變量,而不是在.h文件中。無論您需要使用變量,只需「包含」一個.h文件。 –