简体   繁体   中英

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:

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() . 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:

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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