static const in c++ class: undefined reference

后端 未结 5 879
Happy的楠姐
Happy的楠姐 2021-02-18 21:17

I have a class for local use only (i.e., its cope is only the c++ file it is defined in)

class A {
public:
    static const int MY_CONST = 5;
};

void fun( int b         


        
5条回答
  •  野的像风
    2021-02-18 22:05

    I am having a very strange situation

    template class Strange {
    
    public:
      static const char gapchar='-';
      };
    
    template void Strange method1 {
          char tmp = gapchar;
    }
    
    template void Strange method2 {
        char tmp = gapchar;
    }
    

    I include the above class, it has been working for several years.

    I added another method, essentially the same signature and just reading the gapchar.

    I got undefined error only for the third method, even I am using all three methods.

    Then I changed the way I initialize the static variable by

    not initializing in the class definition:

    static const char gapchar;
    
    template const char Strange::gapchar='-';
    

    This solved the problem. I could not figure out why the old way of initializing int or char type (the only two types allowed) inside the class definition section stop working for only one of the methods but not others.

提交回复
热议问题