static const in c++ class: undefined reference

后端 未结 5 876
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:59

    You can also save the const value to a local variable.

    class A {
    public:
        static const int 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` 
        int l = std::min( j, b);  // works
    }
    

提交回复
热议问题