如何使用QVector at或operator []获取元素的指针 [英] How to use QVector at or operator[] to get a pointer to the element

查看:1899
本文介绍了如何使用QVector at或operator []获取元素的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到一个 QVector 元素的指针,所以我可以使用该对象在其他地方, at()方法给我一个 const T& 值和 operator [] 给我一个 T& 值。

I would love to get a pointer to a QVector element so I can use that object elsewhere however the at() method gives me a const T& value and the operator[] gives me a T& value.

我很困惑如何使用这些来获取指针,所以我将使用相同的对象,复制构造函数。

I'm confused on how to use these to get a pointer so that I will use the same object instead of using a copy constructor.

推荐答案

A T& ,它是参考

引用看起来很像指针:它们很轻,并且可以用来修改底层对象。只有,您使用与直接对象相同的语法(带点而不是箭头),以及您可能想在文章中检查的其他一些差异。

References look a lot like pointers : they are light, and can be used to modify the underlying object. Only, you use them with the same syntax as direct objects (with dots instead of arrows), and some other differences you may want to check out in the article.

编辑Vector中当前的对象,可以使用 vector [i] .action(); 。这将从向量中的对象调用action()方法,而不是从副本。你也可以移交对其他函数的引用(只要它们引用参数),它们仍然指向同一个对象。

To edit an object currently inside the Vector, you can use for instance vector[i].action();. This will call the action() method from the object inside the vector, not on a copy. You can also hand over the reference to other functions (provided they take reference arguments), and they will still point to the same object.

你也可以得到地址来自引用的对象: Object * pObject =&

You can also get the adress of the object from a reference : Object* pObject = & vector[i]; and use it as any pointer.

如果你真的需要指向对象的指针,你也可以使用Vector的指针: QVector< Object *>向量;
然而,这需要你处理创建/销毁,你不需要一个Vector对象。

If you really need pointers to objects, you can also use a Vector of pointers : QVector<Object*> vector; However, this requires you to handle creation / destruction, which you don't need with a Vector of objects.

现在,如果你想要一个指向Vector本身的指针,只要做 QVector< Object> * pVector =& vector;

Now, if you want a pointer to the Vector itself, just do QVector<Object> *pVector = &vector;

这篇关于如何使用QVector at或operator []获取元素的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆