//头文件VECTOR.H
////////////////////////////////////////////////////////////////
#ifndef VECTOR_H_
#define VECTOR_H_
#include<iostream>
namespace VECTOR//名称空间
{
class vector//类定义
{
private://私有数据
double x;
double y;
double mag;
double ang;
char mode;
void set_mag();
void set_ang();
void set_x();
void set_y();
public:
vector();
vector(double n1,double n2,char form='r');
void set(double n1,double n2,char form='r');
~vector();
double xval()const{return x;}
double yval()const{return y;}
double magval()const{return mag;}
double angval()const{return ang;}
void polar_mode();
void rect_mode();
//重载
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 &a);
friend std::ostream & operator<<(std::ostream &os,const vector &v);
};
}
#endif
//////////////////////////////////////////////////////////////////////
// ///////////////////实现文件//////////////////////////
#include<cmath>
#include"vector.h"
using namespace std;
namespace VECTOR
{
const double Rad_to_deg=57.2957795130823;
void vector::set_mag(){mag=sqrt(x*x+y*y);}
void vector::set_ang()
{if(x==0.0 && y==0.0)
ang=0.0;
else
ang=atan2(y,x);
}
void vector::set_x(){x=mag*cos(ang);}
void vector::set_y(){y=mag*sin(ang);}
vector::vector(){x=y=mag=ang=0.0;mode='r';}
vector::vector(double n1,double n2,char form)
{
mode=form;
if(form=='r')
{x=n1;y=n2;
set_mag();
set_ang();}
else if(form=='p')
{mag=n1;ang=n2/Rad_to_deg;
set_x();
set_y();}
else
{cout<<"错误!!!"<<endl;
x=y=mag=ang=0.0;
mode='r';}
}
void vector::set(double n1,double n2,char form)
{
mode=form;
if(form=='r')
{
x=n1;
y=n2;
set_mag();
set_ang();
}
else if(form=='p')
{mag=n1;
ang=n2/Rad_to_deg;
set_x();
set_y();
}
else
{cout<<"错误!!!"<<endl;
x=y=mag=ang=0.0;
mode='r';
}
vector::~vector()//提示有错误!!
{
}
void vector::polar_mode()
{mode='p';}
void vector::rect_mode()
{mode='r';}
//重载函数定义(编译没问题但连接错误,为什么???)
//出错提示:
//
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(n*x,n*y);}
vector operator*(double n,const vector &a)
{return a*n;}
std::ostream & operator<<(std::ostream &os,const vector &v)
{
if(v.mode=='r')
os<<"(x,y)=("<<v.x<<","<<v.y<<")";
else if(v.mode=='p')
os<<"(m.a)=("<<v.mag<<","<<v.ang*Rad_to_deg<<")";
else
os<<"错误!!!";
return os;
}
}
/////////////////////////////////////////////////////////////////