不能引用函数“ Vector :: operator =(const Vector&)throw()”(隐式声明)-该函数已删除

时间:2019-07-11 14:02:59

标签: c++ const deleted-functions

我有一个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...

现在,当我尝试制作两个私有变量PIEPSILON const时,它将在运算符重载线附近产生标题错误。如果我将其设为const static,则调用:

function call must have a constant value in a constant expression

acos(0.0)上。如果我尝试将其设为static constexpr,也会发生相同的情况。这些消息是什么意思,我该如何解决?

1 个答案:

答案 0 :(得分:0)

您的问题是,当您拥有operator =()合格的类成员时,隐式const将被删除 [需要引用] 。在您的*this = ...运算符中,执行+=不再有效。

您有几个简单的选择:

  • PIEPSILON移动到班级之外;可能进入所有内容都在其中的名称空间,或者进入常量名称空间,等等。
  • 您可以在运营商中明确设置*this =...而不是x, y, z
  • 重载operator =()运算符以执行上述操作

如果您认为需要在其他地方使用PIEPSILON,我建议使用第一个,否则建议使用第三个。无论哪种情况,使用您的Vector类都不会感到头疼,因为您可以使用=运算符来复制它们。

编辑

您还询问了错误的含义。我不能说我见过

function call must have a constant value in a constant expression

之前,但可能与问题Constexpr Math Functions

有关