gpt4 book ai didi

c++ - 为什么我收到错误 : invalid operands to binary expression after overloaded += operand?

转载 作者:行者123 更新时间:2023-12-04 14:03:07 28 4
gpt4 key购买 nike

我正在尝试为一个简单的数学 Vector 类重载 += 运算符,以对两个 vector 的元素求和,如下所示:

vector1 += vector2

部分Vector2D.h:

#ifndef _VECTOR2D_H_
#define _VECTOR2D_H_

class Vector2D
{
public:

Vector2D():x(0),y(0){}
~Vector2D(){}

/* All the mathematical operation ... */

// Overloading operators
Vector2D& operator+=(const Vector2D& rhs);
Vector2D& operator*=(const Vector2D& rhs);
Vector2D& operator/=(const Vector2D& rhs);
Vector2D& operator-=(const Vector2D& rhs);

private:

double x;
double y;
};

然后是Vector2D.cpp部分:

#include "Vector2D.h"

Vector2D& Vector2D::operator+=(const Vector2D& rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}

现在,在 .cpp 类中,我想使用运算符:

void MovingObject::move()
{
m_pVelocity += m_pAcceleration;
m_pVelocity->limit(m_fMax_speed);
m_pPosition += m_pVelocity();
m_pAcceleration->zero();
}

变量m_pVelocitym_pAccelerationm_pPosition 都是Vector2D* 指针。

当我尝试编译时,这是我从编译器得到的:

compiler's result

为什么会这样?我读了很多论文,也看过很多例子,它们都有效,但我的不行。

我错过了什么吗?

最佳答案

看起来这条线上有两个指针

m_pVelocity += m_pAcceleration;

所以你需要取消引用它们才能使用这个运算符

*m_pVelocity += *m_pAcceleration;

关于c++ - 为什么我收到错误 : invalid operands to binary expression after overloaded += operand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69395260/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com