如何返回向量对象

How to return a vector object?

本文关键字:向量 对象 返回 何返回      更新时间:2023-10-16

我很困惑要返回向量对象,所以请指导我。谢谢。

我的代码:

struct Vector3D
{
    float x, y, z;
};
class Vertex
{
public:
    std::vector<Vector3D> xyz;
    std::vector<Vector3D> Getxyz()
    {
        return xyz; // what it returns? reference or copy of this object.
    }
Vector3D& getVec(int i) 
{ 
    return this->xyz[i]; // is it OK?
}
void addVec(Vector3D p) 
{ 
    this->xyz.push_back(p); 
}
};
void Somefunction()
{
    Vertex* p = new Vertex;
    p->Getxyz().push_back(Vector3D(0,0,0)); // 1. is it valid and correct?
Vector3D vec = p->getVec(0); // 2. is it valid and correct?
}

不正确。Getxyz()返回临时。您可以push_back该临时性的元素,但不会影响xyz,因为它仅是该对象的 copy 。如果您想突变xyz,则需要返回参考

std::vector<Vector3D>& Getxyz();