0

我正在尝试重载 Vector2D 类的 * 运算符,以便我可以执行以下操作: object * double(不工作) 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);
}
4

1 回答 1

2
const Vector2D operator *(const Vector2D& vector1, const Vector2D& vector2);

对于双 * 向量,这应该是

const Vector2D operator *(double d, const Vector2D& vector2);

而对于 vector * double 它应该是

// overloads * operator for Vector2D * double
    const Vector2D operator *(double d) const;
于 2013-02-07T07:33:11.833 回答