错误C2804:二进制'operator +'有太多参数(用VC 120编译)

A.B*_*.B. 3 c++ operator-overloading operators

编写我自己的矢量类(用于游戏引擎)并在Visual Studio 2013 CPlusPlus项目中重载'+'运算符(使用VC运行时120),它会引发编译器错误:

错误:此操作员功能的参数太多.

Vector.hpp以下文件中的代码段.

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我在这做错了什么?不想让我的运算符超载非成员函数.

Gar*_*365 13

operator+在类内定义时,运算符的左操作数是当前实例.所以,申报超载operator+你有两个选择

  • 在类内部,只有一个参数是右操作数
  • 在课外,有两个参数,左右操作数.

选择1:课外

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;
}
Run Code Online (Sandbox Code Playgroud)

选择2:内部课堂

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;
    }

};
Run Code Online (Sandbox Code Playgroud)

您可以在此处看到如何声明运算符:C/C++运算符