2015-03-30 75 views
0

我的問題可能很愚蠢,但我無法通過名稱空間共享一個值。通過名稱空間共享值

namespace AceEngine 
{ 
    namespace Graphics 
    { 
     namespace Interface 
     { 
      void drawDebugScreen() 
      { 
       // I want to access AceEngine::System::Version from here. 
      } 
     } 
    } 

    namespace System 
    { 
     string Version("DEBUG"); 
    } 
} 

如何訪問此字符串?

編輯:

ae.cpp

#include "stdafx.h" 
#include "sha256.h" 
#include <iostream> 
#include <string> 
using std::cout; 
using std::cin; 
using std::endl; 
using std::getline; 
using std::string; 

namespace AceEngine 
{ 
    namespace Graphics 
    { 
     namespace Interface 
     { 
      void drawDebugScreen() 
      { 
       cout << "Version: " << AceEngine::System::Version << endl; 
      } 
      class Window{}; 
     } 
    } 
    namespace System 
    { 
     class User{}; 
     void pause(){cin.get();} 
     extern string Version("DEBUG"); 
    } 
} 

ae.h

#pragma once 
#include "stdafx.h" 
#include <string> 
using std::string; 

namespace AceEngine 
{ 
    namespace Graphics 
    { 
     namespace Interface 
     { 
      void drawDebugScreen(); 
      class Window{}; 
     } 
    } 

    namespace System 
    { 
     class User{}; 
     void pause(); 
     extern string Version; 
    } 
} 

我刪除的無用部分(我留下了一些類來說明有東西在命名空間和它的不是無用的)

+0

什麼是錯誤信息? – immibis 2015-03-31 07:46:40

回答

1

一如既往,名稱需要在使用前聲明。

您可能想要在標題中聲明它,以便可以從任何源文件中使用它。聲明一個全局變量時,您需要extern

namespace AceEngine { 
    namespace System { 
     extern string Version; 
    } 
} 

或者,如果你只需要在這個文件中,你可以只移動System命名空間來任何需要它。

更新:現在你已經發布完整的代碼,問題是源文件不包含標題。

+0

我已經有一個頭文件;並且該字符串已被聲明。我試圖使用「AceEngine :: System :: Version」來訪問「extern string Version」,但沒有爲編譯器聲明。 – 2015-03-30 18:42:30

+0

@ K-WARE:在這種情況下,請更新問題以顯示您嘗試過的方式以及它的工作方式。在你發佈的代碼中,唯一的問題是它沒有在那個時候聲明。如果編譯器說它沒有聲明,那麼它幾乎肯定不是。 – 2015-03-30 18:44:00

+0

@ K-WARE:你有一個標題,但你不包含它;所以這個字符串沒有被聲明。 – 2015-03-31 09:37:28

0

有必要將字符串的聲明放在其使用點之前。

#include <iostream> // for std::cout 

namespace AceEngine 
{ 
    namespace System 
    { 
     string Version("DEBUG"); // declare it here 
    } 

    namespace Graphics 
    { 
     namespace Interface 
     { 
      void drawDebugScreen() // access it in here 
      { 
       std::cout << AceEngine::System::Version << '\n; 
      } 
     } 
    } 

} 

int main() 
{ 
    AceEngine::Graphics::Interface::drawDebugScreen(); 
    return 0; 
} 

如果您需要嵌套命名空間的數量,那麼您可能會過度考慮您的設計。但這是另一回事。