1

Look at my code below. I made a class Vector2D. I overloaded the + operator and the * operator. In the main function I test these 2 overloaded operators. The only thing I want to add to this is the following: I want to overload the >> operator(?) so when I use >>, I can type in a vector. (so the x and the y component). Then I want to overload the << operator(?) so when I use <<, the program will return me my inputted vector.

#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;
}

The only problem is, I dont know how to do this. Could someone help me^.^?? Thanks in advance.

Earless
  • 173
  • 2
  • 3
  • 9

1 Answers1

1

You need to declare these as friend functions to your Vector2D class (these may not meet your exact need and may require some formatting tweaking):

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;
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • Ok, that looks good. Thanks for that. But how can I use them now? Like I want to use the >> how can I read in a vector now? – Earless Sep 24 '13 at 20:58
  • Okay never mind. I figured it out. Thank you so much for the help :D – Earless Sep 24 '13 at 21:52