代码之家  ›  专栏  ›  技术社区  ›  Paul Wicks asgeo1

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

  •  23
  • Paul Wicks asgeo1  · 技术社区  · 15 年前


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

    4 回复  |  直到 7 年前
        1
  •  65
  •   Drakosha    15 年前

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

    int Foo::bar = you_initial_value_here;
    

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

        2
  •  17
  •   C. K. Young    15 年前

    Foo::bar 必须在标题之外单独定义。在你的 .cpp 文件,请这样说:

    int Foo::bar = 0;  // or whatever value you want
    
        3
  •  16
  •   Artyom    15 年前

    您需要添加一行:

    int Foo::bar;
    

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

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

    foo.cpp

    int Foo::bar=0;
    int Foo::adder() { ... }
    
        4
  •  2
  •   BattleTested_закалённый в бою Fritz R.    9 年前

    要在类中使用静态变量,首先必须为静态变量(初始化)提供一个值generaly(无localy),然后才能访问类中的静态成员:

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