class 文件中的 C++ 对象实例化

C++ Object Instantiation In a class file

我正在用矢量 class 制作一个 module/library,我希望它能正确地完成。

class Vector3 {
public:
    float x, y, z;
public:
    Vector3();
    Vector3(float a, float b, float c);
    float length();
    void normalize();
    Vector3* dotproduct(Vector3 *rhs);
    Vector3* crossproduct(Vector3 *rhs);
    Vector3* add(Vector3 *rhs);
    Vector3* subtract(Vector3 *rhs);
};

我的疑问是手术后我应该如何return一个新的Vector3

目前,我在每个操作中动态分配一个新的 Vector3 然后我 return 它。

当我使用我的操作时:

Vector3 *v = v2->crossproduct(v3);

我是否应该将操作更改为:

Vector3 Vector3::crossproduct(Vector3 *rhs){
    float a = y * rhs->z - z * rhs->y;
    float b = z * rhs->x - x * rhs->z;
    float c = x * rhs->y - y * rhs->x;
    Vector3 res(a, b, c);
    return res ;
}

并使用:

Vector3 v = v2->crossproduct(v3);

或者我最终会丢失向量吗? 因为我正在尝试创建一个库,所以正确的方法是什么? 在堆栈分配,还是在堆分配?

我是这样实现这些操作的:

Vector3 Vector3::crossproduct(const Vector3& rhs){
    float a = y * rhs.z - z * rhs.y;
    float b = z * rhs.x - x * rhs.z;
    float c = x * rhs.y - y * rhs.x;
    Vector3 res(a, b, c);
    return res ;
}

要使用此运算符,您只需使用以下语法:

Vector v1, v2;
auto product = v1.crossproduct(v2);

return as 值很可能被复制省略优化掉了,所以你不必担心。由于 rhs 未被修改,将其作为 const ref& 传递是最快的方法。