For the Vector2D class, overload the + operator so that it returns the sum of tw
ID: 3682706 • Letter: F
Question
For the Vector2D class, overload the + operator so that it returns the sum of two vectors. The sum of two-dimensional vectors A and B is a new vector with x component given by Ax + Bx and y component given Ay + By. Note you will need to define a two argument constructor as well. Overload the insertion operator << such that vectors are printed as (Ax,AY) Overload the array operator [] so that vec_object[x] outputs the x component and vec_object[y] outputs the y component.
Below is the testing program.
#include "vector2D.h"
int main()
{
Vector2D A, B, C;
A.setX(1.0);
A.setY(2.0);
B.setX(3.0);
B.setY(4.0);
cout << A << " " << B << endl;
cout << "The dot product A.B is " << A*B << endl;
C = A + B;
cout << C << endl;
cout << C['x'] << " " << C['y'] << endl;
return 0;
}
Explanation / Answer
///////// vector2D.h //////////////
#include <iostream>
using namespace std;
class Vector2D{
private:
double X;
double Y;
public:
Vector2D();
void setX(double x);
void setY(double y);
Vector2D operator +(const Vector2D& b);
double &operator[](char c);
friend ostream & operator << (ostream &out, const Vector2D &c);
};
////////////////////// vector2D.cpp //////////////////////////////////
#include<iostream>
#include "vector2D.h"
using namespace std;
Vector2D::Vector2D(){
X = 0;
Y = 0;
}
void Vector2D::setX(double x){
X = x;
}
void Vector2D::setY(double y){
Y = y;
}
Vector2D Vector2D::operator+(const Vector2D& b)
{
Vector2D sum;
sum.X = this->X + b.X;
sum.Y = this->Y + b.Y;
return sum;
}
ostream &operator<<( ostream &output, const Vector2D &D )
{
output << "(" << D.X << ", " << D.Y<<")";
return output;
}
double &Vector2D:: operator[](char c)
{
if(c == 'x')
return this->X;
else
return this->Y;
}
int main()
{
Vector2D A, B, C;
A.setX(1.0);
A.setY(2.0);
B.setX(3.0);
B.setY(4.0);
cout << A << " " << B << endl;
C = A + B;
cout <<"C: "<< C << endl;
cout << C['x'] << " " << C['y'] << endl;
return 0;
}
/*
Output:
(1, 2) (3, 4)
C: (4, 6)
4 6
*/