class C++ 中的静态全局变量

Static global variable in a class C++

我正在尝试创建一个将由 class 的所有实例共享的变量,该实例中的所有方法都可以访问它。这样任何实例都可以 read/write 数据 from/to 其他实例。 我尝试了以下方法:

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++
  }

我试图在网上搜索,但所有示例都在函数或方法中演示静态变量,我没有在 class

中找到任何静态全局变量

您必须在编译单元的顶层定义变量(例如myClass.cc):

#include "myClass.h"

int myClass::id = 0;