如何返回向量对象
How to return a vector object?
我很困惑要返回向量对象,所以请指导我。谢谢。
我的代码:
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();
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 迭代时从向量和内存中删除对象
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 如何创建从同一类继承的不同对象的向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 从多个源构造一个对象,包括一个对象向量
- 在C 中,是否有可能在不兼容类型的std ::向量对象之间传输不同类型的缓冲区
- 将向量对象存储在共享指针投掷错误中
- E0312,C2664尝试将向量对象作为函数参数传递时错误
- 相对于向量对象的两个成员,找到两个向量的相交的有效方法
- 将数据从文件读取到向量对象
- C 向量对象访问
- 向量对象声明后的括号是什么意思
- 2向量对象指向相同的分配内存
- 如何返回向量对象
- 传递单个或向量对象时没有重载函数的实例
- 指向数组和向量对象的指针
- 向量对象库,可以存储其他对象类型的对象
- 如何从另一个向量/对象集构造新的向量/指针集