关于类的编译
  • 板块学术版
  • 楼主zhangbo1000
  • 当前回复10
  • 已保存回复10
  • 发布时间2024/8/10 19:42
  • 上次更新2024/8/10 20:59:40
查看原帖
关于类的编译
760291
zhangbo1000楼主2024/8/10 19:42

例如下面一段代码:

#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。

2024/8/10 19:42
加载中...