简体   繁体   中英

Initialize static member in C++

From what I have understood, the reason you initialize a static member in a .cpp file and not in a .h is so there's no risk to get several instances of the member.Take this example then:

   //Foo.h
   #ifndef FOO_H
   #define FOO_H

   class Foo{
      static int a;

   }; 
   int Foo::a = 95; 
   #endif

The preprocessor directives make sure that this .h file is only compiled once, which ensures there is only one instance of the static member. Is this possible to do instead of initiate the static member in a .cpp file?

No, it only assures that Foo.h is included once per compilation unit ( .cpp file). Not in the entire project. You should define the static member within Foo.cpp

Consider having two source code files, a.cpp and b.cpp , that both include the header. Since they're compiled independently of each other, the header guard will not work, you will end up with two object files ao and bo that both define Foo:a . Trying to link them together will fail.

This will cause a linker error if the header is included in multiple .cpp files (translation units):

//a.cpp
#include <Foo.h>

//b.cpp
#include <Foo.h>

After compilation, a.obj contains a definition of Foo::a and b.obj contains a definition of Foo::b . If an attempt is made to link these two .obj files into a single binary a multiple definition error will occur.

No, the include guards ensure that the header is included at most once per compilation unit . If your program has multiple compilation units ( .cpp files) including the header then you will end up with multiple definitions for Foo::a .

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