通过命名空间共享值

Sharing values through namespaces

本文关键字:共享 命名空间      更新时间:2023-10-16

我的问题可能很愚蠢,但我不能通过名称空间共享值。

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;
}

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