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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include <cmath>
#include <iostream>
#include "Vector.h"
namespace VECTOR
{
constexpr double Rad_to_deg = 57.2957795130823;
// Vector::Vector() <-- defaulted
Vector::Vector(double n1, double n2, char form)
{ reset(n1, n2, form); }
void Vector::reset(double n1, double n2, char form)
{
if(form == 'r') {
mode = RECT;
x = n1;
y = n2;
return;
}
if(form == 'p') {
mode = POL;
double mag = n1;
double ang = n2 / Rad_to_deg;
set_x(mag, ang);
set_y(mag, ang);
return;
}
mode = RECT;
x = y = 0.0;
std::cout << "Incorrect 3rd argument to Vector() -- "
"vector set to 0\n";
}
// Vector::~Vector() <-- defaulted
double Vector::xval() const { return x; }
double Vector::yval() const { return y; }
double Vector::magval() const { return set_mag(); }
double Vector::angval() const { return set_ang(); }
void Vector::polar_mode() // set to polar mode
{ mode = POL; }
void Vector::rect_mode() // set to rectangular mode
{
// This is illogical: since you don't store any more the values
// for mag and ang, you can't calculate x and y.
// This method should ask for new x and y values, or for new ang and
// mag and calculate x and y straight on.
mode = RECT;
}
// operator overloading
// add two Vectors
Vector Vector::operator+(const Vector& b) const
{ return Vector(x + b.x, y + b.y); } // relying on mode default value
// means facing troubles when the
// interface is modified.
// subtract Vector b from a
Vector Vector::operator-(const Vector& b) const
{ return Vector(x - b.x, y - b.y); }
// reverse sign of Vector
Vector Vector::operator-() const
{ return Vector(-x, -y); }
// multiple vector by n
Vector Vector::operator*(double n) const
{ return Vector(n * x, n * y); }
// friend methods
// multiply n by Vector a
Vector operator*(double n, const Vector& a)
{ return a * n; }
// display rectangular coordinates if mode is r,
// else display polar coordinates if mode is p
std::ostream& operator<<(std::ostream& os, const Vector& v)
{
switch(v.mode) {
case Vector::Mode::RECT:
os << "(x,y) = (" << v.x << ", " << v.y << ")";
break;
case Vector::Mode::POL:
os << "(m,a) = (" << v.magval() << ", "
<< v.angval() << ")";
break;
default:
os << "Vector object mode is invalid";
break;
}
return os;
}
double Vector::set_mag() const { return std::sqrt(x * x + y * y); }
double Vector::set_ang() const
{
if(x == 0.0 && y == 0.0) { return 0.0; }
else { return atan2(y, x); }
}
void Vector::set_x(double mag, double ang) { x = mag * cos(ang); }
void Vector::set_y(double mag, double ang) { y = mag * sin(ang); }
} // end namespace VECTOR
|