如何在C++中构造静态全局变量

Jac*_*ble 0 c++ global-variables

我在编译/链接一组类时遇到了一些麻烦,其中一些类处理一个共同的全局变量.

基本上,我在类A中声明并定义了一个extern变量foo,并在类B和C中访问/更新它.

相关代码如下所示:

extern string foo; // declare it <=== compiler error "storage class specified for foo"
Run Code Online (Sandbox Code Playgroud)

B.cpp

include A.h  
string foo; // define it  

main () {   
...  
foo = "abc";      
}  
Run Code Online (Sandbox Code Playgroud)

C.cpp

include A.h  
cout << foo; // print it  
Run Code Online (Sandbox Code Playgroud)

我当前的错误是"为foo指定的存储类".但是,我想知道这是否是正确的方法.我应该使用静态变量吗?任何帮助都非常感激,因为我已经在这至少一个小时了.

GMa*_*ckG 6

由于你的错误在外部,我猜它不知道类型是什么.

你有包括字符串吗?

#include <string>

如果是这样,你需要把std::它放在它面前:

#include <string>
extern std::string foo;
Run Code Online (Sandbox Code Playgroud)

请注意,请确保您不在头文件中使用任何using指令(using namespace stdusing std::string),因为这会强制每个起诉您的头文件的人都这样做,这是不好的做法.

编辑

......但这就是我编码的方式.

你确定吗?我刚试过这个,它在VC++和g ++中都运行得很好:

#include <string>

extern std::string foo;
Run Code Online (Sandbox Code Playgroud)

B.cpp

#include "A.h"

std::string foo;

int main (void)
{   
    foo = "abc";      
}
Run Code Online (Sandbox Code Playgroud)

C.cpp

#include "A.h"
#include <iostream>

int some_function(void)
{   
    std::cout << foo << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

试试看,看看它是否有效.