c++ - 从外部更改命名空间变量值 (C++)

标签 c++ namespaces extern

考虑以下命名空间:

// foo.h
namespace foo
{
    extern int bar;
}

//foo.cpp
namespace foo
{
    extern int bar = 42;
}

有没有办法在项目的其他地方(即不在命名空间内)更改 bar 的值?

我的意思是:

// in some other .cpp file
#include foo.h

int setBar(int x)
{
    foo::bar = x;
}

最佳答案

is there a way to change the value of bar somewhere else in the project (i.e, not inside the namespace)?

是的,almost exactly as you've shown 。 示例代码中的唯一问题是您在定义 foo::bar 变量的 foo.cpp 文件中使用了 extern。您需要从 foo.cpp 中删除 extern:

#include <iostream>

// foo.h
namespace foo
{
    extern int bar; // use extern in header file to declare a variable
}

// foo.cpp
namespace foo
{
    int bar = 42; // no extern in cpp file.
}

int setBar(int x)
{
    std::cout << "old foo::bar: " << foo::bar << std::endl;
    foo::bar = x;
    std::cout << "new foo::bar: " << foo::bar << std::endl;
}

int main()
{
    setBar(999);
}

输出:

old foo::bar: 42
new foo::bar: 999

关于c++ - 从外部更改命名空间变量值 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836249/

相关文章:

c# - MarshalAs(UnmanagedType.LPWStr) 和 Marshal.PtrToStringUni() 之间的区别

c++ - 在卷 DICOM 图像上设置 vtkLookupTable

c++ - 为什么priority_queue pop函数不删除栈顶元素?

c++ - 如何将私有(private)指针作为 const 返回到指针列表?

javascript - 通过 JavaScript 动态触发命名空间方法

r - 将包命名空间导入默认命名空间

c++ - 如何在 GPU 而不是 CPU 上运行 qt 应用程序

c# - VS2017 C# 导入 WinForms 生成命名空间错误

我可以从 PIC C18 中的 main.c 访问 source.c 中的并集吗?

c - 带有函数名称的 extern 关键字