如何在命名空间中初始化外部变量

How to initialize extern variables in a namespace

我有一个 global.h 看起来像:

#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 中初始化它,但是 w/e 我正在做,它不工作......请指教。这是主要的样子:

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

基本上我会遇到 "unresolved external symbol" 错误,我不确定如何修复它。感谢任何帮助!

编辑:虽然解决这个问题很高兴,但欢迎提出其他建议。我只想轻松(并不意味着全局,但我不介意)访问对象之类的子系统。

您应该在 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()
{
    ...
}

线条

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 中不要定义变量。他们为变量赋值。它们需要在所有函数之外定义。最好在与声明它们的 .h 文件相对应的 .cpp 文件中定义它们。在您的情况下,该文件应该是 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>();
   }
}

或者在 C++17 中:

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