請看下面的代碼。我做了一個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。 –