C ++)E0349没有与这些操作数匹配的运算符

问题描述 投票:1回答:1

我想进行标量*向量运算,例如5 *(2,3)=(10,15)。

e0349-如下所示运行后,没有运算符与这些操作数匹配。

但是我不知道那里出了什么问题。

这是我的代码。

#include <iostream>
using namespace std;

class Vector {
public:
    Vector();
    Vector(float x, float y);

    float GetX() const;
    float GetY() const;

    static Vector operator*(const float x, const Vector b); //Scalar * Vector operation

private:
    float x;
    float y;
};

int main() {
    Vector a(2, 3);
    Vector b = 5 * a; //Error's here ! 


    cout << a.GetX() << ", " << a.GetY() << endl;
    cout << b.GetX() << ", " << b.GetY() << endl;
}

Vector::Vector() : x(0), y(0) {}
Vector::Vector(float x, float y) : x(x), y(y) {}

float Vector::GetX() const { return x; }
float Vector::GetY() const { return y; }

Vector Vector::operator*(const float a, const Vector b) {
    return Vector(a * b.x, a * b.y);
}
'''
c++ vector overloading operator-keyword
1个回答
1
投票

您应该在此处将operator*设为非成员函数,并且由于您正在访问其中的private成员,因此可以将其标记为friend

class Vector {
public:
    Vector();
    Vector(float x, float y);

    float GetX() const;
    float GetY() const;

    friend Vector operator*(const float x, const Vector b); //Scalar * Vector operation

private:
    float x;
    float y;
};

...

Vector operator*(const float a, const Vector b) {
    return Vector(a * b.x, a * b.y);
}

LIVE

或(不设friend

class Vector {
public:
    Vector();
    Vector(float x, float y);

    float GetX() const;
    float GetY() const;

private:
    float x;
    float y;
};

Vector operator*(const float x, const Vector b); //Scalar * Vector operation

...

Vector operator*(const float a, const Vector b) {
    return Vector(a * b.GetX(), a * b.GetY());
}

LIVE

© www.soinside.com 2019 - 2024. All rights reserved.