Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error C2804: binary 'operator +' has too many parameters (compiling with VC 120)

Writing my own vector class (for a game engine) and overloading '+' operator in Visual Studio 2013 CPlusPlus project (using VC runtime 120), it is throwing me compiler error:

Error: too many parameters for this operator function.

Code snippet from Vector.hpp file below.

Vector.hpp

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, Vector& p2) //Error is thrown here...
    {
        Vector temp(p1);
        return temp += p2;
    }
};

enter image description here

What am I doing wrong here? Don't want to make my operator overload non-member function.

like image 222
A.B. Avatar asked Mar 11 '16 15:03

A.B.


1 Answers

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+(const Vector & p2)
    {
        Vector temp(*this);
        temp += p2;
        return temp;
    }

};

You can see how should be declared operators here : C/C++ operators

like image 126
Garf365 Avatar answered Nov 13 '22 06:11

Garf365