Unresolved external symbol on static class members

后端 未结 5 1477
温柔的废话
温柔的废话 2020-11-22 02:04

Very simply put:

I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other clas

5条回答
  •  情书的邮戳
    2020-11-22 02:39

    Static data members declarations in the class declaration are not definition of them. To define them you should do this in the .CPP file to avoid duplicated symbols.

    The only data you can declare and define is integral static constants. (Values of enums can be used as constant values as well)

    You might want to rewrite your code as:

    class test {
    public:
      const static unsigned char X = 1;
      const static unsigned char Y = 2;
      ...
      test();
    };
    
    test::test() {
    }
    

    If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:

    .H :

    class test {
    public:
    
      static unsigned char X;
      static unsigned char Y;
    
      ...
    
      test();
    };
    

    .CPP :

    unsigned char test::X = 1;
    unsigned char test::Y = 2;
    
    test::test()
    {
      // constructor is empty.
      // We don't initialize static data member here, 
      // because static data initialization will happen on every constructor call.
    }
    

提交回复
热议问题