我正在设计一个 Vector3D 类,并希望能够轻松访问一些常用向量,例如笛卡尔基向量和 origo。下面是一种使用静态成员的方法。这是实现这一目标的正确方法吗?性能将是一个关键点。
矢量.h
#include <iostream>
class Vector3D {
public:
Vector3D(double x=0.0, double y=0.0, double z=0.0) :
x_(x),
y_(y),
z_(z) {};
inline void print() const {
std::cout << x_ << " " << y_ << " " << z_ << std::endl;
}
// Predefined Vectors
static Vector3D ZERO;
static Vector3D X;
static Vector3D Y;
static Vector3D Z;
double x_, y_, z_;
};
向量.cpp
#include "vector.h"
// Predefined vectors
Vector3D Vector3D::ZERO = Vector3D(0.0f, 0.0f, 0.0f);
Vector3D Vector3D::X = Vector3D(1.0f, 0.0f, 0.0f);
Vector3D Vector3D::Y = Vector3D(0.0f, 1.0f, 0.0f);
Vector3D Vector3D::Z = Vector3D(0.0f, 0.0f, 1.0f);
然后可以像这样使用该类:
主文件
#include "vector.h"
int main()
{
Vector3D o = Vector3D::ZERO;
Vector3D x = Vector3D::X;
Vector3D y = Vector3D::Y;
Vector3D z = Vector3D::Z;
o.print();
x.print();
y.print();
z.print();
return 0;
}