static const in c++ class: undefined reference

后端 未结 5 883
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 21:50

    // initialize static constants outside the class
    
    class A {
    public:
        static const int MY_CONST;
    };
    
    const int A::MY_CONST = 5;
    
    void fun( int b ) {
        int j = A::MY_CONST;  // no problem
        int k = std::min( A::MY_CONST, b ); // link error: 
                                                // undefined reference to `A::MY_CONST` 
    }
    

提交回复
热议问题