加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:17:41 所属栏目:百科 来源:网络整理
导读:我只有一个本地使用的课程(即它的上课只是在它定义的c文件) class A {public: static const int MY_CONST = 5;};void fun( int b ) { int j = A::MY_CONST; // no problem int k = std::minint( A::MY_CONST,b ); // link error: // undefined reference to
我只有一个本地使用的课程(即它的上课只是在它定义的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上编译时,只能在第二个语句中获取未定义的引用错误.

有什么建议么?

解决方法

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读