本文介绍了错误C2804:二进制“运算符+"具有太多参数(使用VC 120编译)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写我自己的向量类(用于游戏引擎)并在Visual Studio 2013 CPlusPlus项目中重载"+"运算符(使用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:

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

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

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

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

推荐答案

在类中定义operator+时,运算符的左操作数是当前实例.因此,要声明operator+的重载,您有2个选择

When operator+ is defined inside class, left operand of operator is current instance. So, to declare a overload of operator+ you have 2 choices

  • 内部类,只有一个参数是正确的操作数
  • 类之外,具有两个参数,左和右操作数.

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

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

};

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

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

这篇关于错误C2804:二进制“运算符+"具有太多参数(使用VC 120编译)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:28