我想做标量*向量运算,比如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);
}
'''
您应该在此处将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);
}
实时
或者(不使其成为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());
}
实时