关于constexpr定义的结构体
  • 板块学术版
  • 楼主Flanksy
  • 当前回复2
  • 已保存回复2
  • 发布时间2022/12/11 16:57
  • 上次更新2023/10/24 07:58:15
查看原帖
关于constexpr定义的结构体
662295
Flanksy楼主2022/12/11 16:57

以下结构体(手动实现的复数类)在使用const定义常量时能通过编译,但使用constexpr时编译错误,想知道为什么会出现这种情况。

struct Complex{
	double x,y;
	Complex(double x=0,double y=0){this->x=x,this->y=y;}
	Complex operator+(Complex x)const{
		return Complex(this->x+x.x,y+x.y);
	}
	Complex operator-(Complex x)const{
		return Complex(this->x-x.x,y-x.y);
	}
	Complex operator*(Complex x)const{
		return Complex(this->x*x.x-y*x.y,this->x*x.y+y*x.x);
	}
	Complex operator/(Complex x)const{
		double tmp=x.x*x.x+x.y*x.y;
		return Complex((this->x*x.x+y*x.y)/tmp,(y*x.x-this->x*x.y)/tmp);
	}
	Complex conju(){return Complex(x,-y);}
	double mod2(){return x*x+y*y;}
	double mod(){return __builtin_sqrt(mod2());}
};

例:

const Complex x=Complex(1,1);
const Complex x(1,1);
//以上两种可以通过编译
constexpr Complex x=Complex(1,1);
constexpr Complex x(1,1);
/*以上两种不可通过编译 显示:
[Error] the type 'Complex' of 'constexpr' variable 'x' is not literal.
[Note] 'Complex' is not literal because:
[Note] 'Complex' is not an aggregate, does not have a trivial default constructor, and has no 'constexpr' constructor that is not a copy or move constructor.
*/

上网查找了一下,并没有理解,求比较清晰的解释。

2022/12/11 16:57
加载中...