Why won't my C++ program link when my class has static members?

后端 未结 5 1865
长情又很酷
长情又很酷 2021-01-18 04:55

I have a little class called Stuff that I want to store things in. These things are a list of type int. Throughout my code in whatever classes I use I want to be able to a

相关标签:
5条回答
  • 2021-01-18 05:05

    Static data members have to be defined outside class declarations, much like methods.

    For example:

    class X {
        public:
            static int i;
    };
    

    Must also have the following:

    int X::i = 0; // definition outside class declaration
    
    0 讨论(0)
  • 2021-01-18 05:07

    Static member have to be declared in the class but defined in the unit (cpp file) where it is really located.

    The only exception is in case the class is template: in this case you have to define the member outside the class, but you have to provide it too with the class declaration, in the header file.

    0 讨论(0)
  • 2021-01-18 05:10

    Mentioning a static member in a class declaration is a declaration only. You must include one definition of the static member for the linker to hook everything up properly. Normally you would include something like the following in a Stuff.cpp file:

    #include "Stuff.h"
    
    list<int> Stuff::things;
    

    Be sure to include Stuff.cpp in your program along with Main.cpp.

    0 讨论(0)
  • 2021-01-18 05:10

    Just For your Information, why this works is that in C++ all global variables (including static global) are created before the execution of the main function begins.

    0 讨论(0)
  • 2021-01-18 05:26

    Stuff::things is only declared, but it is not defined.

    please use:

    // Stuff.cpp
    #include "Stuff.h"
    
    std::list<int> Stuff::things;
    

    Added: it is also a good practice to protect your header files against multiple inclusion:

    // Stuff.h
    #ifndef STUFF_H_
    #define STUFF_H_
    
    #include <list>
    
    class Stuff {
        public:
           static std::list<int> things;
    };
    
    #endif
    
    0 讨论(0)
提交回复
热议问题