【发布时间】:2020-06-11 09:21:01
【问题描述】:
我正在尝试创建一个变量,该变量将由类的所有实例共享,并且实例中的所有方法都可以访问它。以便任何实例都能够从/向其他实例读取/写入数据。 我尝试了以下方法:
class myClass
{
public: static int id; // declaring static variable for use across all instances of this class
myClass() //constractor
{
//here I tried few ways to access and 'id' as static and global variable inside the class:
id = 0; // compilation (or linker) error: undefined reference to `myClass::id'
int id = 0; // compilation success, but it does not refer to the static variable.
static int id = 0; //compilation success, it is static variable that shared among other instances, but other methods cannot access this variable, so its local and not global.
}
// example for another function that needs to access the global static variable.
int init_id()
{
id++
}
我尝试在网上搜索,但所有示例都演示了函数或方法内部的静态变量,我没有在类中找到任何静态全局变量
【问题讨论】:
-
只删除静态变量是不够的,你还需要在某个地方定义它们。我敢肯定,这有一个副本。简而言之:将定义
int myClass::id = 0添加到某个 cpp 文件中 -
下次当问题是关于编译器错误时,请在您的问题中包含错误
标签: c++ class global-variables static-variables