2013-09-24 63 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

相關問題