c类中的静态常量:未定义的引用

新手上路,请多包涵

我有一个仅供本地使用的类(即,它的对应只是它定义的 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`
}

所有代码都驻留在 同一个 c++ 文件中。在windows上使用VS编译时,完全没有问题。

但是,在 Linux 上编译时,我得到 undefined reference 仅针对第二个语句的错误。

有什么建议么?

原文由 user2379182 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 514
1 个回答

std::min<int> ’s arguments are both const int& (not just int ), ie references to int .而且您不能传递对 A::MY_CONST 的引用,因为它 _没有定义_(仅 _声明_)。

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

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

const int A::MY_CONST; // definition (no value needed)

原文由 gx_ 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题