简体   繁体   English

静态成员必须初始化吗?

[英]Static member has to be initialized?

The code is as below: 代码如下:

#include <iostream>

using namespace std;

class A {
    static int id_;

public:
    static void setId(int id) {
        id_ = id;
    }
    static int getId() {
        return id_;
    }
};

int main()
{
    A::setId(10);
    cout << A::getId() << endl;
    return 0;
}

When I compile it in Xcode , Mac OS , there's an error message: 当我在Mac OS的 Xcode中编译它时,出现错误消息:

Undefined symbols for architecture x86_64:
  "A::id_", referenced from:
      A::setId(int) in main.o
      A::getId() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

If I add the line: 如果我添加以下行:

int A::id_ = 10;

before the main() . main()之前。 Then, everything is fine. 然后,一切都很好。 What's the reason with it? 这是什么原因呢?

Variables need to be declared and defined and the draft C++ standard section 9.4.2 Static data members says: 需要声明定义变量,并且C ++标准草案9.4.2节“ 静态数据成员”说:

The declaration of a static data member in its class definition is not a definition [...] 静态数据成员的类定义中的声明不是定义[...]

so it must be defined , which is why you need to add: 因此必须定义它,这就是为什么需要添加:

int A::id_ = 10;

and to see this more clearly, we see that: 为了更清楚地看到这一点,我们看到:

int A::id_ ;

is sufficient, we don't have to initialize A::id_ just define it. 足够了,我们不必初始化A::id_即可定义它。

You may also want to read this previous thread: What is the difference between a definition and a declaration? 您可能还想阅读上一个线程: 定义和声明之间有什么区别? .

As Steve points out when you move to using header files you will need to define your variable in the cpp file since you do not want more than one definition. 正如Steve指出的那样,当您转到使用文件时,您将需要在cpp文件中定义变量,因为您不需要多个定义。

一旦创建了类对象,某些编译器将不允许在没有初始化的情况下创建静态变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM