[英]Access a method of a class contained as a vector of pointers to that class
我有一個指向以下對象的指針向量:
std::vector<queuedImage*> imgBuffer;
我通過引用將其傳遞給類的構造函數:
processThread::processThread(std::vector<queuedImage*> &queueRef);
在類processThread中,我定義了:
std::vector<queuedImage*> *q;
在構造函數中,我進行分配:
q = &queueRef;
當我訪問已經填充了對象的向量的元素時,訪問向量的大小符合預期:
int qSize = q->size();
這使我認為這應該是有效的:
q[0]->getData()
其中getData是queuedImage的成員。
但是,當我對此進行編譯時,它顯然無效:
error: base operand of ‘->’ has non-pointer type ‘std::vector<queuedImage*>’
但是當我使用。 運算符:
q[0].getData()
我收到編譯錯誤:
error: ‘class std::vector<queuedImage*>’ has no member named ‘getData’
我認為我必須錯誤地訪問了該方法,但是我不確定該怎么做。 有人有什么想法嗎?
謝謝!
當您執行q[0]
,您沒有訪問向量的第一個元素,實際上是在取消引用指針。 q[0]
== *q
==一個向量。
您要做的是在q
指向的向量上調用[0]
。 為此,您必須首先取消引用q
:
(*q)[0]->getData()
這應該是
(*q)[0]->getData();
但是,為什么當您已經通過引用接受vector時卻不必要地創建指向vector的指針。
除了修復語法錯誤以解引用指向向量的不必要指針
(*q)[0]->getData()
您應該認真考慮使用智能指針,例如
std::vector<std::unique_ptr<queuedImage>>
要么
std::vector<std::unique_ptr<queuedImage>>
將引用保存在向量中,而不是原始指針。
實際使用哪種智能指針類型取決於您的用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.