@cxm-2016
2016-09-06T09:51:38.000000Z
字数 1822
阅读 2596
c++
no
作者:陈小默
本节内容用来复习前两节知识点
定义向量的加减乘除操作和内积、外积。
vector.h
#ifndef primer_vector_h
#define primer_vector_h
class Vector{
private:
double x,y;
double length,angle;
double PI=3.1415926535898;
public:
Vector(double x,double y);
Vector(double length,float angle);
~Vector();
double getX(){return x;}
double getY(){return y;}
double getLength(){return length;}
double getAngle(){return 180*(angle/PI);}
//operator
Vector operator+(Vector &v){
double x_ = this->x;
double y_ = this->y;
x_+=v.getX();
y_+=v.getY();
return Vector(x_,y_);
}
Vector operator-(Vector &v){
double x_ = this->x;
double y_ = this->y;
x_-=v.getX();
y_-=v.getY();
return Vector(x_,y_);
}
Vector operator-(){
double x_ = 0.0-this->x;
double y_ = 0.0-this->y;
return Vector(x_,y_);
}
Vector operator*(double n){
double x_ = n*this->x;
double y_ = n*this->y;
return Vector(x_,y_);
}
Vector operator/(double n){
double x_ = this->x/n;
double y_ = this->y/n;
return Vector(x_,y_);
}
double operator>(Vector &v);//投影
double operator>>(Vector &v);//点乘
double operator*(Vector &v);//叉乘
//friend
friend Vector operator*(double n,Vector &v){
return v * n;
}
};
#endif
实现vector.cpp
#include"stdafx.h"
#include "vector.h"
#include<cmath>
Vector::Vector(double x,double y){
Vector::x = x;
Vector::y = y;
Vector::length = std::sqrt(x*x+y*y);
if(x==0&&y==0){
Vector::angle = 0.0;
}else {
Vector::angle = std::atan2(y,x);
}
}
Vector::Vector(double length,float angle){
Vector::length = length;
Vector::angle = angle*PI/180;
Vector::x=((int(angle)-90)%180==0)?0:length*std::cos(Vector::angle);
Vector::y=(int(angle)%180==0)?0:length*std::sin(Vector::angle);
}
Vector::~Vector(){}
double Vector::operator>(Vector &v){
double l1 = this->length;
double cos = std::cos(std::abs(v.angle-this->angle));
return cos*l1;
}
double Vector::operator>>(Vector &v){
double l2 = v.getLength();
double s = (*this)>v;
return s*l2;
}
double Vector::operator*(Vector &v){
double l1 = this->length;
double l2 = v.getLength();
double sin = std::sin(std::abs(v.angle-this->angle));
return l1*l2*sin;
}