【发布时间】:2022-06-13 20:37:47
【问题描述】:
我正在为我的项目创建一个 Vector2 类,但不能在运算符中使用任何构造函数
我不知道可能出了什么问题,因为这段代码在我之前的项目中没有任何问题。我会很感激你的帮助
class Vector2 {
public:
Vector2() : x(0.0f), y(0.0f) {}
Vector2(float _x,float _y) : x(_x), y(_y) {}
Vector2(float number) : x(number), y(number) {}
Vector2(Vector2& other) : x(other.x), y(other.y) {}
float Length() { return sqrt(x*x + y*y); }
Vector2 operator+(const Vector2& other) { return Vector2(x + other.x, y + other.y); }
Vector2 operator+(float other) { return Vector2(x + other, y + other); }
Vector2 operator-(const Vector2& other) { return Vector2(x - other.x, y - other.y); }
Vector2 operator-(float other) { return Vector2(x - other, y - other); }
Vector2 operator/(const Vector2& other) { return Vector2(x / other.x, y / other.y); }
Vector2 operator/(float other) { return Vector2(x / other, y / other); }
Vector2 operator*(const Vector2& other) { return Vector2(x * other.x, y * other.y); }
Vector2 operator*(float other) { return Vector2(x * other, y * other); }
void operator=(float other) { x = other; y = other; }
void operator=(Vector2 other) { x = other.x; y = other.y; }
bool operator==(Vector2 other) { return (x == other.x && y == other.y ); }
bool operator!=(Vector2 other) { return (x != other.x && y != other.y ); }
void operator+=(Vector2 other) { x += other.x; y += other.y; }
void operator-=(Vector2 other) { x -= other.x; y -= other.y; }
void operator*=(Vector2 other) { x *= other.x; y *= other.y; }
void operator/=(Vector2 other) { x /= other.x; y /= other.y; }
void operator/=(float other) { x /= other; y /= other; }
float x,y;
};
输出:
C:/Users/Dell/Desktop/Voxeler/src/engine/math/vectors.hpp: In member function 'fr::math::Vector2 fr::math::Vector2::operator+(const fr::math::Vector2&)':
C:/Users/Dell/Desktop/Voxeler/src/engine/math/vectors.hpp:101:58: error: cannot bind non-const lvalue reference of type 'fr::math::Vector2&' to an rvalue of type 'fr::math::Vector2'
101 | Vector2 operator+(const Vector2& other) { return Vector2(x + other.x, y + other.y); }
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/Users/Dell/Desktop/Voxeler/src/engine/math/vectors.hpp:97:26: note: initializing argument 1 of 'fr::math::Vector2::Vector2(fr::math::Vector2&)'
97 | Vector2(Vector2& other) : x(other.x), y(other.y) {}
| ~~~~~~~~~^~~~~
C:/Users/Dell/Desktop/Voxeler/src/engine/math/vectors.hpp: In member function 'fr::math::Vector2 fr::math::Vector2::operator+(float)':
C:/Users/Dell/Desktop/Voxeler/src/engine/math/vectors.hpp:102:49: error: cannot bind non-const lvalue reference of type 'fr::math::Vector2&' to an rvalue of type 'fr::math::Vector2'
102 | Vector2 operator+(float other) { return Vector2(x + other, y + other); }
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
【问题讨论】:
-
您的复制构造函数应该通过 const 引用获取值。