2023/9/24
自己写了写书中的vector类
vector.h
#ifndef __VECTOR_H__
#define __VECTOR_H__
#include <iostream>
using namespace std;
namespace VECTOR
{
class Vector
{
public:
enum Mode
{
RECT, // 直角坐标系
POL // 极坐标系
};
private:
double x; // 坐标
double y;
double length; // 长度和角度
double ang;
Mode mode;
void set_x();
void set_y();
void set_length();
void set_ang();
public:
Vector();
Vector(double n1, double n2, Mode form = RECT); // 构造函数,默认使用直角坐标系
void reset(double n1, double n2, Mode form = RECT);
~Vector();
double xVal() const { return x; }
double yVal() const { return y; }
double lengthVal() const { return length; }
double angVal() const { return ang; }
void polMode();
void rectMode();
// 运算符重载
Vector operator+(const Vector &b) const;
Vector operator-(const Vector &b) const;
Vector operator-() const;
Vector operator*(double n) const;
// 友元
friend Vector operator*(double n, const Vector &b);
friend ostream &operator<<(ostream &os, const Vector &v);
};
}
#endif
vector.cpp
#include <cmath>
#include "vector.h"
using namespace std;
namespace VECTOR
{
const double RadToDeg = 45.0 / atan(1.0);
void Vector::set_length()
{
length = sqrt(x * x + y * y);
}
void Vector::set_ang()
{
if (x == 0 && y == 0)
ang == 0;
else
ang = atan2(y, x);
}
void Vector::set_x()
{
x = length * cos(ang);
}
void Vector::set_y()
{
y = length * sin(ang);
}
// 构造函数
Vector::Vector()
{
x = y = length = ang = 0.0;
mode = RECT;
}
Vector::Vector(double n1, double n2, Mode form)
{
mode = form;
if (form == RECT)
{
x = n1, y = n2;
set_length();
set_ang();
}
else if (form = POL)
{
length = n1, ang = n2 / RadToDeg;
set_x();
set_y();
}
else
{
cout << "Incorrect,vector has set to 0." << endl;
form = RECT;
x = y = length = ang = 0;
}
}
void Vector::reset(double n1, double n2, Mode form)
{
mode = form;
if (form == RECT)
{
x = n1, y = n2;
set_length();
set_ang();
}
else if (form = POL)
{
length = n1, ang = n2 / RadToDeg;
set_x();
set_y();
}
else
{
cout << "Incorrect,vector has set to 0." << endl;
form = RECT;
x = y = length = ang = 0;
}
}
// 析构函数
Vector::~Vector()
{
cout << "Vector has been destoryed." << endl;
}
void Vector::polMode()
{
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 &b)
{
return b * n;
}
ostream &operator<<(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.length << ", " << v.ang * RadToDeg << ")";
}
else
os << "Vector object mode is invalid";
return os;
}
}