我有一个Vector
班。当前看起来像这样:
class Vector{
double PI = 2 * acos(0.0);
double EPSILON = 1e-4;
public:
double x,y,z;
Vector() : x(0.0),y(0.0),z(0.0) {}
Vector(double _x,double _y,double _z) : x(_x), y(_y), z(_z){}
// some more code...
Vector& operator += (const Vector &vect) {
*this = *this + vect;
return *this;
}
Vector& operator += (const double &value){
*this = *this - value;
return *this;
}
// some more operator overloading....
inline bool isNearlyEqual (const double &a,const double &b) const{
return std::abs(a - b) < EPSILON;
}
inline double radiansToDegree (const double &radians) const {
return radians * 180.0 / PI;
}
// some more code...
现在,当我尝试制作两个私有变量PI
和EPSILON
const
时,它将在运算符重载线附近产生标题错误。如果我将其设为const static
,则调用:
function call must have a constant value in a constant expression
在acos(0.0)
上。如果我尝试将其设为static constexpr
,也会发生相同的情况。这些消息是什么意思,我该如何解决?
答案 0 :(得分:0)
您的问题是,当您拥有operator =()
合格的类成员时,隐式const
将被删除 [需要引用] 。在您的*this = ...
运算符中,执行+=
不再有效。
您有几个简单的选择:
PI
和EPSILON
移动到班级之外;可能进入所有内容都在其中的名称空间,或者进入常量名称空间,等等。*this =...
而不是x, y, z
。operator =()
运算符以执行上述操作如果您认为需要在其他地方使用PI
和EPSILON
,我建议使用第一个,否则建议使用第三个。无论哪种情况,使用您的Vector
类都不会感到头疼,因为您可以使用=
运算符来复制它们。
编辑
您还询问了错误的含义。我不能说我见过
function call must have a constant value in a constant expression
之前,但可能与问题Constexpr Math Functions
有关