C++栈类小练习
作者:互联网
#ifndef VECTOR_H_
#define VECTOR_H_
#include <iostream>
namespace VECTOR
{
class Vector
{
public:
enum Mode{RECT,POL};
private:
double x;
double y;
double mag;
double ang;
Mode mode;
void setMag();
void setAng();
void setX();
void setY();
public:
Vector();
Vector(double n1, double n2, Mode form = RECT);
~Vector();
void reset(double n1 = 0, double n2 = 0, Mode form = RECT);
double xVal() const { return x; }
double yVal() const { return y; }
double magVal() const { return mag; }
double angVal() const { return ang; }
void polarMode();
void rectMode();
//operator overloading
Vector operator+(const Vector & b) const;
Vector operator-(const Vector & b) const;
Vector operator-() const;
Vector operator*(double n) const;
//friends
friend Vector operator*(double n, const Vector &a);
friend std::ostream & operator<<(std::ostream & os, const Vector & v);
};
}
#endif
#include<cmath>
#include"Vector.h"
using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout;
namespace VECTOR
{
const double RAD_TO_DEG = 45.0 / atan(1.0);
void Vector::setMag()
{
mag = sqrt(x*x + y*y);
}
void Vector::setAng()
{
if (x == 0.0&& y == 0.0)
{
ang = 0.0;
}
else
{
ang = atan2(y, x);
}
}
void Vector::setX()
{
x = mag * cos(ang);
}
void Vector::setY()
{
y = mag * sin(ang);
}
Vector::Vector()
{
x = y = mag = ang = 10.0;
mode = RECT;
}
Vector::Vector(double n1, double n2, Mode form)
{
mode = form;
if (form == RECT)
{
x = n1;
y = n2;
setMag();
setAng();
}
else if (form == POL)
{
mag = n1;
ang = n2;
setX();
setY();
}
else
{
std::cerr << "Vector set to 0";
x = y = mag = ang = 0.0;
mode = RECT;
}
}
void Vector::reset(double n1, double n2, Mode form)
{
mode = form;
if (form == RECT)
{
x = n1;
y = n2;
setMag();
setAng();
}
else if (form == POL)
{
mag = n1;
ang = n2;
setX();
setY();
}
else
{
std::cerr << "Vector set to 0";
x = y = mag = ang = 0.0;
mode = RECT;
}
}
Vector::~Vector()
{
}
void Vector::polarMode()
{
mode = POL;
}
void Vector::rectMode()
{
mode = RECT;
}
Vector Vector::operator+(const Vector & b) const
{
return Vector(x + b.x, y + b.y);
}
Vector Vector::operator-(const Vector & b) const
{
return Vector(x - b.x, y - b.y);
}
Vector Vector::operator-() const
{
return Vector(- x,- y);
}
Vector Vector::operator*(double n) const
{
return Vector(x * n, y * n);
}
Vector operator*(double n, const Vector & a)
{
return (a * n);
}
std::ostream & operator<<(std::ostream & os, const Vector & v)
{
if (v.mode == Vector::RECT)
{
os << "(x,y) = (" << v.x << ',' << v.y << ")";
}
else if (v.mode == Vector::POL)
{
os << "(m,a) = (" << v.mag << "," << v.ang * RAD_TO_DEG << ")";
}
else
{
os << "problem";
}
return os;
}
}
#include"Vector.h"
#include<Windows.h>
using namespace VECTOR;
int main()
{
Vector x(3,4,Vector::RECT);
std::cout << -x << std::endl;
system("pause");
return 0;
}
标签:栈类,ang,const,double,void,练习,C++,Vector,operator 来源: https://blog.csdn.net/qq_41614638/article/details/80523424