例如下面一段代码:
#include<iostream>
using namespace std;
class test{
public:
static constexpr int none=1;
int x;
test(const int& _x=none):x(_x){}
};
int main(){
test* p=new test;
cout<<p->x;
return 0;
}
编译出错:
//文件名为 Untitled5.cpp
C:\Users\Administrator\AppData\Local\Temp\ccY7bsaq.o Untitled5.cpp:(.rdata$.refptr._ZN4test4noneE[.refptr._ZN4test4noneE]+0x0): undefined reference to `test::none'
C:\Users\Administrator\Documents\collect2.exe [Error] ld returned 1 exit status
经过我的反复测试,似乎如果一个常量被定义在类内,并被用在了构造函数参数默认值时,会使得涉及此类的 new 语句报错,而常量在类外定义就不会有这样的错,这是怎么回事?
这是我最早注意到此问题的代码:Link。