2015-03-30 79 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; 
} 

如果您需要嵌套命名空间的数量,那么您可能会过度考虑您的设计。但这是另一回事。