c++ - 在 C++ 中访问静态类变量?

标签 c++ class static

重复:
C++: undefined reference to static class member

如果我有这样的类/结构

// header file
class Foo
{
   public:
   static int bar;
   int baz;
   int adder();
};

// implementation
int Foo::adder()
{
   return baz + bar;
}

这不起作用。我收到“未定义的对 `Foo::bar' 的引用”错误。如何在 C++ 中访问静态类变量?

最佳答案

您必须在实现文件中添加以下行:

int Foo::bar = you_initial_value_here;

这是必需的,因此编译器有一个静态变量的位置。

关于c++ - 在 C++ 中访问静态类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743203/

相关文章:

c++ - 具有跨 DLL/SO 使用的静态数据成员的模板类

java - 为什么接口(interface)是静态的?

c++ - 防止 QTable 在编辑时选择所有文本

c++ - 了解工厂方法和静态变量分配的返回值优化 (Visual Studio)

c++ - 替代全局变量/常量

c++ - QSqlQuery不起作用

c++ - std::map<struct, int> 我需要析构函数吗?

python - 设计用于删除 Tkinter Text Widget Content 的线程不进行操作。

python - 在 python 2.5.1 或更早版本中使用属性和 setter

ios - swift/ios 如何检查我的 TableView 是否嵌入在 uitableview Controller 实例中?