c ++类中的static const:未定义的引用

17 c++ linker static-members

我有一个仅供本地使用的类(即,它的cope只是它定义的c ++文件)

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

void fun( int b ) {
    int j = A::MY_CONST;  // no problem
    int k = std::min<int>( A::MY_CONST, b ); // link error: 
                                            // undefined reference to `A::MY_CONST` 
}
Run Code Online (Sandbox Code Playgroud)

所有代码都驻留在同一个c ++文件中.在Windows上使用VS进行编译时,完全没有问题.
但是,在Linux上编译时,我undefined reference只得到第二个语句的错误.

有什么建议?

gx_*_*gx_ 20

std::min<int>的参数都是const int&(不只是int),即引用int.并且您无法传递引用,A::MY_CONST因为它未定义(仅声明).

.cpp课外提供文件中的定义:

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

const int A::MY_CONST; // definition (no value needed)
Run Code Online (Sandbox Code Playgroud)


小智 6

// 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<int>( A::MY_CONST, b ); // link error: 
                                            // undefined reference to `A::MY_CONST` 
}
Run Code Online (Sandbox Code Playgroud)