c_cpp 矢量类示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 矢量类示例相关的知识,希望对你有一定的参考价值。

ll#include <iostream>
#include <cstdio>

class Vector3
{
  	private:
		float m_x;
		float m_y;
		float m_z;
	public:
		Vector3();
		Vector3(float x, float y, float z);
		void set(float x, float y, float z);
		void get(Vector3 &vec3);
		Vector3 operator+(const Vector3 &vec3);
		Vector3 operator-(const Vector3 &vec3);
		Vector3 operator*(const Vector3 &vec3);
		Vector3 operator/(const Vector3 &vec3);

		Vector3 &operator+=(const Vector3 &vec3);
		Vector3 &operator-=(const Vector3 &vec3);
		Vector3 &operator*=(const Vector3 &vec3);
		Vector3 &operator/=(const Vector3 &vec3);

		float operator[](const int index);
		void printVal();
};

Vector3::Vector3()
{
	m_x = 0;
	m_y = 0;
	m_z = 0;
}

Vector3::Vector3(float x, float y, float z)
{
	m_x = x;
	m_y = y;
	m_z = z;
}

void Vector3::set(float x, float y, float z)
{
	m_x = x;
	m_y = y;
	m_z = z;
}

Vector3 Vector3::operator+(const Vector3 &vec3)
{
	return Vector3(vec3.m_x + m_x, vec3.m_y + m_y, vec3.m_z + m_z);
}

Vector3 Vector3::operator-(const Vector3 &vec3)
{
	return Vector3(m_x - vec3.m_x, m_y-vec3.m_y, m_z - vec3.m_z);
}

Vector3 Vector3::operator*(const Vector3 &vec3)
{
	return Vector3(m_x * vec3.m_x, m_y * vec3.m_y, m_z * vec3.m_z);
}

Vector3 Vector3::operator/(const Vector3 &vec3)
{
	return Vector3(m_x / vec3.m_x, m_y / vec3.m_y, m_z / vec3.m_z);
}

Vector3& Vector3::operator+=(const Vector3 &vec3)
{
	m_x += vec3.m_x;
	m_y += vec3.m_y;
	m_z += vec3.m_z;
	return *this;
}

Vector3& Vector3::operator-=(const Vector3 &vec3)
{
	m_x -= vec3.m_x;
	m_y -= vec3.m_y;
	m_z -= vec3.m_z;
	return *this;
}

Vector3& Vector3::operator*=(const Vector3 &vec3)
{
	m_x *= vec3.m_x;
	m_y *= vec3.m_y;
	m_z *= vec3.m_z;
	return *this;
}

Vector3& Vector3::operator/=(const Vector3 &vec3)
{
	m_x /= vec3.m_x;
	m_y /= vec3.m_y;
	m_z /= vec3.m_z;
	return *this;
}

float Vector3::operator[](const int index)
{
	if(index==0){return m_x;}
	else if(index==1){return m_y;}
	else if(index==2){return m_z;}
	else {return -1;}
}

void Vector3::printVal()
{
	printf("(%f,%f,%f)\n", m_x, m_y, m_z);
}

int main()
{
	Vector3 a = Vector3(2.0,2.0,3.0);
	Vector3 b = Vector3(1.0,2.0,3.0);

	a =  b - a;
	a +=b;
	float test = a[4];
	std::cout<<test<<std::endl;

	a.printVal();


	std::cout<<"Hello, world"<<std::endl;
	return 0;
}

以上是关于c_cpp 矢量类示例的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 将矢量写入文件

c_cpp 删除删除矢量

c_cpp 打印矢量

c_cpp 比较矢量

c_cpp 数组与矢量C ++

c_cpp 数组初始化矢量