C ++对象实例化在类文件中

时间:2017-10-16 15:27:13

标签: c++ class memory-management allocation

我正在制作一个带有矢量类的模块/库,我希望它能够正确地完成它。

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);
};

我的疑问是如何在手术后返回新的Vector3

目前,我在每个操作中动态分配一个新的Vector3,然后我将其返回。

当我使用我的操作时:

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);

或者我最终会丢失矢量? 既然我试图创建一个库,那么正确的方法是什么? 在堆栈或堆中分配?

1 个答案:

答案 0 :(得分:3)

我实现了这样的操作:

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);

最有可能通过复制省略来优化返回值,因此您不必担心这一点。由于rhs未被修改,因此将其作为const ref&是最快的方法。