【问题标题】:Static global variable in a class C++ [duplicate]C ++类中的静态全局变量[重复]
【发布时间】: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


【解决方案1】:

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

#include "myClass.h"

int myClass::id = 0;

【讨论】:

  • @idclev463035818 哎呀,是的,把我的术语弄混了!已更正!
  • 可以在类里面定义吗?
  • @orenk 不,不是。
猜你喜欢
  • 2018-12-22
  • 2022-01-28
  • 2020-04-06
  • 2015-06-12
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
相关资源
最近更新 更多