Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...