C ++类中的静态常量:未定义的引用 [英] static const in c++ class: undefined reference

查看:246
本文介绍了C ++类中的静态常量:未定义的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仅在本地使用的类(即,它的作用仅仅是它在其中定义的c ++文件)

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 ) {
    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错误.

All the code reside in the same c++ file. When compiling using VS on windows, there is no problem at all.
However, when compiling on Linux I get the undefined reference error only for the second statement.

有什么建议吗?

推荐答案

std::min<int> 的参数都是const int&(不仅仅是int),即int的引用.而且您不能传递对A::MY_CONST的引用,因为它没有定义 (仅声明了 ).

std::min<int>'s arguments are both const int&(not just int), i.e. references to int. And you can't pass a reference to A::MY_CONST because it is not defined (only declared).

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

Provide a definition in the .cpp file, outside the class:

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

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

这篇关于C ++类中的静态常量:未定义的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆