我正在尝试为类Vector2D重载*运算符,以便可以执行以下操作:
对象*两倍(不起作用)
双重*对象(不起作用)
对象*对象(这个很好用)

我收到关于没有操作员采用左手类型的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);
}

最佳答案

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


对于double * Vector,应为

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


对于矢量*两倍,应该是

// overloads * operator for Vector2D * double
    const Vector2D operator *(double d) const;

关于c++ - 重载的问题* double的运算符* obj和obj * double,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14745809/

10-17 01:41