[关闭]
@cxm-2016 2016-09-06T09:51:38.000000Z 字数 1822 阅读 2596

C++:实现数学向量Vector

c++ no
作者:陈小默


本节内容用来复习前两节知识点
定义向量的加减乘除操作和内积、外积。

vector.h

  1. #ifndef primer_vector_h
  2. #define primer_vector_h
  3. class Vector{
  4. private:
  5. double x,y;
  6. double length,angle;
  7. double PI=3.1415926535898;
  8. public:
  9. Vector(double x,double y);
  10. Vector(double length,float angle);
  11. ~Vector();
  12. double getX(){return x;}
  13. double getY(){return y;}
  14. double getLength(){return length;}
  15. double getAngle(){return 180*(angle/PI);}
  16. //operator
  17. Vector operator+(Vector &v){
  18. double x_ = this->x;
  19. double y_ = this->y;
  20. x_+=v.getX();
  21. y_+=v.getY();
  22. return Vector(x_,y_);
  23. }
  24. Vector operator-(Vector &v){
  25. double x_ = this->x;
  26. double y_ = this->y;
  27. x_-=v.getX();
  28. y_-=v.getY();
  29. return Vector(x_,y_);
  30. }
  31. Vector operator-(){
  32. double x_ = 0.0-this->x;
  33. double y_ = 0.0-this->y;
  34. return Vector(x_,y_);
  35. }
  36. Vector operator*(double n){
  37. double x_ = n*this->x;
  38. double y_ = n*this->y;
  39. return Vector(x_,y_);
  40. }
  41. Vector operator/(double n){
  42. double x_ = this->x/n;
  43. double y_ = this->y/n;
  44. return Vector(x_,y_);
  45. }
  46. double operator>(Vector &v);//投影
  47. double operator>>(Vector &v);//点乘
  48. double operator*(Vector &v);//叉乘
  49. //friend
  50. friend Vector operator*(double n,Vector &v){
  51. return v * n;
  52. }
  53. };
  54. #endif

实现vector.cpp

  1. #include"stdafx.h"
  2. #include "vector.h"
  3. #include<cmath>
  4. Vector::Vector(double x,double y){
  5. Vector::x = x;
  6. Vector::y = y;
  7. Vector::length = std::sqrt(x*x+y*y);
  8. if(x==0&&y==0){
  9. Vector::angle = 0.0;
  10. }else {
  11. Vector::angle = std::atan2(y,x);
  12. }
  13. }
  14. Vector::Vector(double length,float angle){
  15. Vector::length = length;
  16. Vector::angle = angle*PI/180;
  17. Vector::x=((int(angle)-90)%180==0)?0:length*std::cos(Vector::angle);
  18. Vector::y=(int(angle)%180==0)?0:length*std::sin(Vector::angle);
  19. }
  20. Vector::~Vector(){}
  21. double Vector::operator>(Vector &v){
  22. double l1 = this->length;
  23. double cos = std::cos(std::abs(v.angle-this->angle));
  24. return cos*l1;
  25. }
  26. double Vector::operator>>(Vector &v){
  27. double l2 = v.getLength();
  28. double s = (*this)>v;
  29. return s*l2;
  30. }
  31. double Vector::operator*(Vector &v){
  32. double l1 = this->length;
  33. double l2 = v.getLength();
  34. double sin = std::sin(std::abs(v.angle-this->angle));
  35. return l1*l2*sin;
  36. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注