【问题标题】:Accessing static class variables in C++?在 C++ 中访问静态类变量?
【发布时间】:2010-10-19 02:19:03
【问题描述】:

重复:
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++ 中访问静态类变量?

【问题讨论】:

  • 请注意,您缺少一个 ';'在类定义之后。

标签: c++ class static


【解决方案1】:

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

int Foo::bar = you_initial_value_here;

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

【讨论】:

    【解决方案2】:

    这是正确的语法,但是,Foo::bar 必须在标头之外单独定义。在您的.cpp 文件之一中,这样说:

    int Foo::bar = 0;  // or whatever value you want
    

    【讨论】:

    • 你好 Chris,如果我们在 c++ 中有这么多公共静态类成员变量(非多线程源代码)有什么问题吗?我已将一些全局变量作为公共静态变量移到一个类中。
    【解决方案3】:

    你需要添加一行:

    int Foo::bar;
    

    这将为您定义一个存储。类中静态的定义类似于“extern”——它提供符号但不创建它。即

    foo.h

    class Foo {
        static int bar;
        int adder();
    };
    

    foo.cpp

    int Foo::bar=0;
    int Foo::adder() { ... }
    

    【讨论】:

      【解决方案4】:

      为了在类中使用静态变量,首先你必须给你的静态变量(初始化)一个一般的值(没有本地化),然后你可以访问类中的静态成员:

      class Foo
      {
         public:
         static int bar;
         int baz;
         int adder();
      };
      
      int Foo::bar = 0;
      // implementation
      int Foo::adder()
      {
         return baz + bar;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-18
        • 1970-01-01
        • 1970-01-01
        • 2017-01-13
        • 2015-06-12
        • 2011-03-05
        • 1970-01-01
        相关资源
        最近更新 更多