请看下面的代码。我做了一个Vector2D类。我重载了+运算符和*运算符。在主函数中我测试了这两个重载操作符。我想添加的唯一一件事情是:我想重载>>操作符(?),所以当我使用>>时,我可以输入一个向量。 (所以x和y分量)。然后我想超载运算符(?),所以当我使用< <时,程序会返回我输入的向量。在C++中重载“>>”和“<<”
#include <iostream>
using namespace std;
class Vector2D
{
public:
Vector2D();
Vector2D(double X = 0, double Y = 0)
{
x = X;
y = Y;
};
double x, y;
Vector2D operator+(const Vector2D &vect) const
{
return Vector2D(x + vect.x, y + vect.y);
}
double operator*(const Vector2D &vect) const
{
return (x * vect.x) + (y * vect.y);
}
};
int main()
{
cout << "Adding vector [10,10] by vector [5,5]" << endl;
Vector2D vec1(10, 10);
Vector2D vec2(5, 5);
Vector2D vec3 = vec1 + vec2;
cout << "Vector = " << "[" << vec3.x << "," << vec3.y << "]" << endl;
cout << "Dot product of vectors [5,5] and [10,10]:" << endl;
double dotp = vec1 * vec2;
cout << "Dot product: " << dotp << endl;
return 0;
}
唯一的问题是,我不知道该怎么做。有人可以帮助我^^^?提前致谢。
请阅读:http://stackoverflow.com/questions/4421706 /运算符重载?rq = 1 –
[请看这里](http://stackoverflow.com/questions/4066666/and-operator-overloading) – user2422869
可读性:您可能没有运算符*,但是有两个独立函数改为scalar_product和vector_product。 –