2013-09-24 65 views
1

请看下面的代码。我做了一个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; 
} 

唯一的问题是,我不知道该怎么做。有人可以帮助我^^^?提前致谢。

+1

请阅读:http://stackoverflow.com/questions/4421706 /运算符重载?rq = 1 –

+0

[请看这里](http://stackoverflow.com/questions/4066666/and-operator-overloading) – user2422869

+0

可读性:您可能没有运算符*,但是有两个独立函数改为scalar_product和vector_product。 –

回答

1

你需要声明这些作为friend功能,您Vector2D类(这些可能无法完全满足您的需要,可能需要一些格式的调整):

std::ostream& operator<<(std::ostream& os, const Vector2D& vec) 
{ 
    os << "[" << vec.x << "," << vec.y << "]"; 
    return os; 
} 

std::istream& operator>>(std::istream& is, Vector2D& vec) 
{ 
    is >> vec.x >> vec.y; 
    return is; 
} 
+0

好吧,看起来不错。感谢那。但我现在怎么使用它们?就像我想使用>>我现在怎么读矢量? – Earless

+0

好的没关系。我想到了。非常感谢你的帮助:D – Earless

相关问题