// Vector2D method to find the size (length) of a vector
double Vector2D::Magnitude() const
{
// Use pythogoras theorom to find lenght/size of vector (h^2 = x^2 + y^2)
return sqrt(x * x + y * y);
}
// Overloaded stream operator ** FIX TO MATCH EXAMPLE OUTPUT **
// Note the '<<' operator is not part of the Vector2D class directly.
// Q. How does this work and why?
std::ostream& operator<< (std::ostream& os, const Vector2D& v)
{
return os << "(" << " *contents of 2D vector object's <x,y> should be here* " << ")";
}
This is the .h file
#pragma once
#include <iostream>
class Vector2D
{
private:
double x;
double y;
public:
Vector2D(double x = 0.0, double y = 0.0 );
~Vector2D(void);
// Useful methods to work on the 2D vector
double Vector2D::Magnitude() const;
cout << "Initial values of vectors (overload '<<' stream operator):" << endl;
cout << " a = " << a << ", b = " << b << ", c = " << c << endl;
cout << endl << "Simple vector methods:" << endl;
cout << " magnitude of a = " << a.Magnitude() << endl;
cout << " magnitude of b = " << b.Magnitude() << endl;
cout << endl << "Comparing vectors (overloading boolean operators '<', '>', etc.):" << endl;
cout << " (a < b) = " << std::boolalpha << (a < b) << endl;
// cout << " (a > b) = " << std::boolalpha << (a > b) << endl;
cout << endl << "Copying vectors (overloading the assignment operator '='):" << endl;
c = a;
cout << " (a == c) = " << std::boolalpha << (a == c) << endl;
//cout << " (a != c) = " << std::boolalpha << (a != c) << endl;
//cout << " (a >= c) = " << std::boolalpha << (a >= c) << endl;
cout << endl << "Assign vector 'a' results of adding 'a + b' (overloading the operator '+=')" << endl;
a += b;
cout << " (a += b) = " << a << endl;
//cout << endl << "Scalar multiplication (overloading the operator '*=')" << endl;
//a *= -1.0;
//cout << " a = " << a << endl;
//cout << endl << "Scalar division (overloading the operator '/=')" << endl;
//b /= 0.5;
//cout << " b = " << b << endl;
//b /= 0.0; // Handle error case: displpay error message and assign 'x=quiet_NaN()' and 'y=quiet_NaN()'
//cout << " b = " << b << endl;