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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/743203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:04:03  来源:igfitidea点击:

Accessing static class variables in C++?

c++classstatic

提问by Paul Wicks

Duplicate:
C++: undefined reference to static class member

重复:
C++:对静态类成员的未定义引用

If I have a class/struct like this

如果我有这样的类/结构

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

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

This doesn't work. I get an "undefined reference to `Foo::bar'" error. How do I access static class variables in C++?

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

回答by Drakosha

You must add the following line in the implementationfile:

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

int Foo::bar = you_initial_value_here;

This is required so the compiler has a place for the static variable.

这是必需的,以便编译器为静态变量留出空间。

回答by Chris Jester-Young

It's the correct syntax, however, Foo::barmust be defined separately, outside of the header. In one of your .cppfiles, say this:

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

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

回答by Artyom

You need add a line:

您需要添加一行:

int Foo::bar;

That would define you a storage. Definition of static in class is similar to "extern" -- it provides symbol but does not create it. ie

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

foo.h

foo.h

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

foo.cpp

文件

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

回答by BattleTested

for use of static variable in class, in first you must give a value generaly (no localy) to your static variable (initialize) then you can accessing a static member in class :

要在类中使用静态变量,首先您必须为静态变量(初始化)提供一个通用值(无局部),然后您可以访问类中的静态成员:

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

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