[英]C++ access global integer from class header file
我有一个声明一个类的头文件,并且我希望该类访问已在主cpp C ++文件(即,与该类的文件不同的另一个文件)中声明的整数。 我一直在Google上搜索,没有发现任何相关信息。 我怎样才能做到这一点?
要在源文件之间共享全局变量,请使用extern
关键字。
main.cpp
#include "foo.h"
int global_var=0;
int main()
{
foo();
return 0;
}
foo.h
#ifndef FOO_H
#define FOO_H
extern int global_var;
void foo();
#endif
foo.cpp
#include "foo.h"
int foo()
{
global_var=1;
}
将main.cpp中的整数移到一个函数中,使其在其中静态化,让该函数返回对其的引用,然后将该函数放入其自己的头文件中,该头文件包括类头文件(或实现文件,如果适用)。
integer.h:
#ifndef INTEGER_H // use some better, longer name here
#define INTEGER_H
int &Integer();
#endif
integer.cpp:
#include "integer.h"
int &Integer()
{
static int i = 0;
return i;
}
像这样访问整数:
int x = Integer(); // copy
Integer() = 123; // assign
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.