我正在尝试为类Vector2D重载*运算符,以便我可以执行以下操作: 对象*双(不工作) double * object(不工作) object * object(这个工作正常)
我收到的错误消息是关于如何没有操作员使用左手类型的Vector2D,或左手类型的double等等。我不确定我在尝试实现各种*重载。我甚至为自动类型转换添加了一个构造函数:
#include <iostream>
using namespace std;
struct Vector2D
{
public:
// constructors
Vector2D(double X=0, double Y=0);
Vector2D(double number);
// mutators
void setX(double X);
void setY(double Y);
//accessors
double getX() const;
double getY() const;
// overloads * operator for Vector2D * double
const Vector2D operator *(const Vector2D& vector2) const;
// overloads * operator for Vector2D * Vector2D -- returns dot product
double operator *(const Vector2D& vector2);
private:
// vector components
double x;
double y;
};
// overloads * operator for double * Vector2D
const Vector2D operator *(const Vector2D& vector1, const Vector2D& vector2);
int main()
{
int x, y;
Vector2D vecA, vecB, vecC;
cout << "Enter x and y components (separated by a space) for vector A: ";
cin >> x >> y;
vecA.setX(x);
vecA.setY(y);
vecB = vecA * 25.0;
cout << vecB.getX() << endl << vecB.getY() << endl;
vecC = 25.0 * vecA;
cout << vecC.getX() << endl << vecC.getY() << endl;
return 0;
}
Vector2D::Vector2D(double X, double Y) {
x = X;
y = Y;
}
Vector2D::Vector2D(double number) {
x = y = number;
}
void Vector2D::setX(double X) {
x = X;
}
void Vector2D::setY(double Y) {
y = Y;
}
double Vector2D::getX() const {
return x;
}
double Vector2D::getY() const {
return y;
}
const Vector2D Vector2D::operator *(const Vector2D& vector2) const {
double newX = x*vector2.x;
double newY = y*vector2.y;
return Vector2D(newX, newY);
}
// Vector2D * Vector2D (returns dot product)
double Vector2D::operator *(const Vector2D& vector2) {
double dotProd = (x*vector2.x) + (y*vector2.y);
return dotProd;
}
// double * Vector2D
const Vector2D operator *(const Vector2D& vector1, const Vector2D& vector2) {
double newX = vector1.getX()*vector2.getX();
double newY = vector2.getX()*vector2.getY();
return Vector2D(newX, newY);
}
答案 0 :(得分:2)
const Vector2D operator *(const Vector2D& vector1, const Vector2D& vector2);
for double * Vector这应该是
const Vector2D operator *(double d, const Vector2D& vector2);
对于vector * double,它应该是
// overloads * operator for Vector2D * double
const Vector2D operator *(double d) const;