向量类的实现

时间:2021-05-28 10:16:23

向量在实现图形学的算法中有很重要的位置 ,下面是 用C++写的一个向量类,实现了一些 基本的 向量操作。

代码清单:

gvector3.h

#ifndef GVECTOR3_H
#define GVECTOR3_H
#include <iostream>
#include <cmath>
using namespace std;


class GVector3
{

public:
float x;
float y;
float z;
// 缺省构造函数
GVector3();
~GVector3();
// 用户构造函数
GVector3(float posX, float posY, float posZ);
//输出向量信息
void getInfo();
//矢量加法
GVector3 operator+(GVector3 v);
//矢量减法
GVector3 operator-(GVector3 v);
//数乘
GVector3 operator*(float n);
//数除
GVector3 operator/(float n);
//向量点积
float dotMul(GVector3 v2);
//向量叉乘
GVector3 crossMul(GVector3 v2);
//获取矢量长度
float getLength();
//向量单位化
void Normalize();
};

#endif // GVECTOR3_H

gvector.cpp

#include "gvector3.h"

GVector3::GVector3()
{
}
GVector3::~GVector3()
{
}
GVector3::GVector3(float posX, float posY, float posZ)
{
x=posX;
y=posY;
z=posZ;
}

GVector3 GVector3::operator+(GVector3 v)
{
return GVector3(x+v.x,v.y+y,v.z+z);
}
GVector3 GVector3::operator-(GVector3 v)
{
return GVector3(x-v.x,y-v.y,z-v.z);
}
GVector3 GVector3::operator*(float n)
{
return GVector3(x*n,y*n,z*n);
}
GVector3 GVector3::operator/(float n)
{
return GVector3(x/n,y/n,z/n);
}
void GVector3::getInfo()
{
cout<<"x:"<<x<<" y:"<<y<<" z:"<<z<<endl;
}
float GVector3::dotMul(GVector3 v2)
{
return (x*v2.x+y*v2.y+z*v2.z);
}
GVector3 GVector3::crossMul(GVector3 v2)
{
GVector3 vNormal;
// 计算垂直矢量
vNormal.x = ((y * v2.z) - (z * v2.y));
vNormal.y = ((z * v2.x) - (x * v2.z));
vNormal.z = ((x * v2.y) - (y * v2.x));
return vNormal;
}
float GVector3::getLength()
{
return (float)sqrt(x*x+y*y+z*z);
}
void GVector3::Normalize()
{
float length=getLength();
x=x/length;
y=y/length;
z=z/length;
}

测试文件:

#include <iostream>
#include "gvector3.h"
using namespace std;

int main()
{
GVector3 v1,v2,v3;
v1=GVector3(1.0,2.0,5.0);
v2=GVector3(3.0,1.0,6.0);
v1=v1-v2;
v1.getInfo();
v2=v2/2;
v2.getInfo();
v3=v1.crossMul(v2);
v3.getInfo();
float a=v1.dotMul(v2);
cout<<"v1 dotMul v2:"<<a<<endl;
cout<<"v3.Length:"<<v3.getLength()<<endl;
v3.Normalize();
cout<<"v3 After nomarlize:"<<endl;
v3.getInfo();
cout << "Hello world!" << endl;
return 0;
}


注意编译命令是:g++  main.cpp gvector3.h gvector3.cpp -o 1

运行结果:

向量类的实现