gpt4 book ai didi

c++ - 如何在 C++ 中的命名空间之间共享变量?

转载 作者:行者123 更新时间:2023-11-30 01:51:12 25 4
gpt4 key购买 nike

我有 C# 背景,所以请问答案是否可以与 C# 相比较。

我有一个包含函数和变量的命名空间,用于为我的程序解析输入。 namespace 在头文件和源文件中定义。我还定义了一个结构,它在我的程序中为每个输入参数都有一个属性,以促进跨类的通信。就像下面的最小工作示例:

mytypes.h

#ifndef _MYTYPES_H_
#define _MYTYPES_H_
namespace MyTypes
{
enum class Par1Opt
{
opt1,opt2
};
struct InputParam_t
{
Par1Opt par1;
int test;
};
}
#endif // _MYTYPES_H_

myinput.h

#ifndef _MYINPUT_H_
#define _MYINPUT_H_
#include <unordered_map>
#include <string>
#include "mytypes.h"
namespace MyInput
{
static const std::string par1 = "par1";
static int testVar;
static MyTypes::InputParam_t inputParam;
static std::unordered_map<MyTypes::Par1Opt, std::string> Par1OptToStr;
void InitVariables(void);
}
#endif // _MYINPUT_H_

我的输入.cpp

#include <unordered_map>
#include <string>
#include "mytypes.h"
#include "myinput.h"
namespace MyInput
{
void InitVariables(void) // set some default values
{
inputParam.par1 = MyTypes::Par1Opt::opt1; // default value
inputParam.test = 10;
Par1OptToStr = std::unordered_map<MyTypes::Par1Opt, std::string>({
{ MyTypes::Par1Opt::opt1, "opt1" },
{ MyTypes::Par1Opt::opt2, "opt2" }
});
testVar = 20;
}
}

main.cpp

#include <iostream>
#include "myinput.h"
int main(int argCount, char* args[])
{
MyInput::InitVariables(); // expect to set MyInput:: variables here
std::cout << MyInput::par1 << " = "
<< MyInput::Par1OptToStr[MyInput::inputParam.par1]
<< std::endl; // par1 =
std::cout << "inputParam.test = " << MyInput::inputParam.test
<< std::endl; // inputParam.test = 0
std::cout << "testVar = " << MyInput::testVar
<< std::endl; // testVar = 0
std::cin.get(); // pause
// none of the values set for the MyInput:: variables inside InitVariables() method
// are available in main
}

问题是:

  1. 为什么 InitVariable() 中设置的值在 main() 中不可用?由于变量是静态的,我希望(主要是 C# 背景)这些值在我使用 #include "myinput.h" 的任何地方都可用。我该如何解决?

  2. 如果我从 myinput.h 的变量声明中删除 static 关键字,则会出现 Multiply defined symbols 错误。为什么?

提前致谢!

最佳答案

当您在 .h 文件中使用 static 说明符声明全局变量时,您在每个包含 .h 文件的翻译单元中创建一个单独的变量,因此 中引用的变量myinput.cpp 与从 main.cpp 引用的变量不同,尽管它们具有相同的名称。

当你创建它时没有说明符,你违反了 One Definition Rule .

您应该做的是在 .h 文件中使用 extern 说明符声明变量,并在其中一个 .cpp 文件中定义它们:

我的输入.h

namespace MyInput
{
extern const std::string par1;
extern int testVar;
}

我的输入.cpp

namespace MyInput
{
const std::string par1 = "par1";
int testVar;
}

关于c++ - 如何在 C++ 中的命名空间之间共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com