通过命名空间共享值
Sharing values through namespaces
我的问题可能很愚蠢,但我不能通过名称空间共享值。
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;
}
}
我删除了无用的部分(我留下了一些类来显示名称空间中有东西,这并不是无用的)
与往常一样,名称在使用前需要声明。
您可能想在头中声明它,这样它就可以从任何源文件中使用。声明全局变量时需要extern
:
namespace AceEngine {
namespace System {
extern string Version;
}
}
或者,如果您只需要在这个文件中使用它,您可以将System
名称空间移到任何需要它的名称空间之前
更新:现在您已经发布了完整的代码,问题是源文件不包括头。
有必要将字符串的声明放在其使用点之前。
#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;
}
如果您需要这么多嵌套的名称空间,那么您可能会过度考虑您的设计。但那是另一回事。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 在命名空间中定义函数还是限定函数
- C++:对不存在的命名空间使用命名空间指令
- 通过继承类使用来自不同命名空间的运算符
- 使用命名空间时出现多个定义错误
- CUDA内核和数学函数的显式命名空间
- 嵌套的匿名命名空间
- CMakeLists.txt中的命名空间表示法
- 类是C++中的命名空间吗
- 在命名空间中使用全局命名空间中的函数
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- '使用命名空间{嵌套在另一个命名空间中的某个命名空间}"
- 是否可以将函数导入命名空间,但不能导出它?
- C++ C++类中的命名空间降级
- 如何使用 soong 命名空间来有条件地编译模块
- 共享库中使用"使用命名空间"定义的符号错误
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?
- 通过命名空间共享值
- 使用跨dll /共享库的命名空间