美文网首页
类内运算符重载报错:参数过多

类内运算符重载报错:参数过多

作者: Jianbaozi | 来源:发表于2019-03-06 14:34 被阅读0次

    When operator+ is defined inside class, left operand of operator is current instance. So, to declare a overload of operator+ you have 2 choices
    inside class, with only one parameter which is right operand
    outside of class, with two parameters, left and right operands.
    Choice 1: outside class

    class Vector
    {
    private:
        double i;
        double j;
        double k;
    public:
        Vector(double _i, double _j, double _k)
        {
            i = _i;
            j = _j;
            k = _k;
        }
    
        Vector& operator+=(const Vector& p1)
        {
            i += p1.i;
            j += p1.j;
            k += p1.k;
            return *this;
        }
    
        //Some other functionality...
    
    
    };
    
    Vector operator+(const Vector& p1, const Vector& p2)
    {
        Vector temp(p1);
        temp += p2;
        return temp;
    }
    

    Choice 2: inside class

    class Vector
    {
    private:
        double i;
        double j;
        double k;
    public:
        Vector(double _i, double _j, double _k)
        {
            i = _i;
            j = _j;
            k = _k;
        }
    
        Vector& operator+=(const Vector& p1)
        {
            i += p1.i;
            j += p1.j;
            k += p1.k;
            return *this;
        }
    
    
    
        Vector operator+(consr Vector & p2)
        {
            Vector temp(*this);
            temp += p2;
            return temp;
        }
    
    };
    

    https://stackoverflow.com/questions/35943537/error-c2804-binary-operator-has-too-many-parameters-compiling-with-vc-120

    相关文章

      网友评论

          本文标题:类内运算符重载报错:参数过多

          本文链接:https://www.haomeiwen.com/subject/mswtpqtx.html