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

gdf31

我正在使用向量类制作模块/库,并且希望它正确执行。

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

还是我最终会丢失向量?由于我正在尝试创建一个库,因此正确的方法是什么?分配在堆栈还是堆中?

越界

我像这样实现这些操作:

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&传递是最快的方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章