Hey guys, I am a sophomore in CS and am having a bit of trouble with operator overloading. My code will not compile and I have exhausted my search through the internet in how to fix this.
My assignment is this:
Write the definition for a class named Vector2D that stores information about a two-dimensional vector. The class should have methods to get and set the x component and the y component, where x and y are integers.
Next, overload the * operator so that it returns the dot product of two vectors. The dot product of two-dimensional vectors A and B is equal to
(Ax * Bx) + (Ay * By)
Next, overload the << and >> operators so that you can write the following code
Vector2D v;
cin >> v;
cout << v;
Finally, write a main program that tests the three overloaded operators.
Sample output
(10,0) * (0,10) = 0
(0,10) * (10,10) = 100
(10,10) * (5,4) = 90
You may use the following main() function:
int main()
{
Vector2D v1, v2;
cin>>v1>>v2;
cout << v1 <<" * "<< v2<< " = " << v1*v2 << endl;
return 0;
}
Here is my code that I cannot get to compile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#include <iostream>
#include <cstdlib>
using namespace std;
class Vector2D
{
public:
Vector2D();
Vector2D(int newx, int newy);
void SetXY(int newx, int newy);
int GetX();
int GetY();
int operator *(const Vector2D& v2);
friend istream& operator >>(istream& instream, Vector2D& vector);
friend ostream& operator <<(ostream& outputStream, Vector2D& vector);
private:
int x,y;
};
Vector2D::Vector2D()
{
x=0;
y=0;
}
Vector2D::Vector2D(int newx, int newy)
{
x=newx;
y=newy;
}
void Vector2D::SetXY(int newx, int newy)
{
x=newx;
y=newy;
}
int Vector2D::GetX()
{
return (x);
}
int Vector2D::GetY()
{
return (y);
}
int Vector2D::operator *(const Vector2D& v2)
{
return (x*v2.x) + (y*v2.y);
}
istream& operator >>(istream& instream, Vector2D& vector)
{
instream >> vector.x;
instream >> vector.y;
return instream;
}
ostream& operator <<(ostream outstream, Vector2D& vector)
{
outstream << vector.GetX();
outstream << vector.GetY();
return outstream;
}
int main()
{
Vector2D v1, v2;
cin>>v1>>v2;
cout << v1 <<" * "<< v2<< " = " << v1*v2 << endl;
return 0;
}
|