2012-02-17 155 views
4

我有一個QList,我已經插入了對象指針。我正試圖遍歷這個QList來讀取這些對象的名稱。每當我這樣做時,我都會得到這些對象的地址,與讀取對象名稱本身相反。我想知道如何能夠讀取對象名稱而不是地址?獲取對象指針指向

QList<MyObject*> newObjectList; 
QList<MyObject*>::iterator i; 

MyObject *pNewObject = new MyObject(name); 
MyObject.append(pNewObject); 

for (i = newObjectList.begin(); i != newObjectList.end(); i++) { 
    cout << "\n" << *i << "\n"; 
} 

回答

3

當您解除引用i時,您需要調用該函數以從您的對象中獲取該名稱。類似這樣的:

for (i = newObjectList.begin(); i != newObjectList.end(); i++) { 
    // i right now is the iterator, and points to a pointer. So this will need to be 
    // dereferenced twice. 
    cout << "\n" << (*i)->getName() << "\n"; 
} 
+0

謝謝。它的工作:)有沒有其他使用箭頭符號( - >)? – Jon 2012-02-17 18:43:56

+0

你可以用*:'(*(* i))。getName();' – 2012-02-17 18:50:12

+0

非常感謝:) – Jon 2012-02-17 18:56:20

2

當你derenference迭代I(即*i)你AA參考MyObject*類型的對象,這是一個指針,你必須取消引用再次,要想讓你的對象的引用:

*(*i) 
+1

'** i'就夠了,括號是沒有必要的。 – Fanael 2012-02-17 18:40:19

+0

我剛剛通過將行更改爲「cout <<」\ n「<< *(* i)<<」\ n「;」但我得到了錯誤「C678:二進制'<<':找不到運算符類型'QTextStream'的左手操作數(或沒有可接受的轉換)」 – Jon 2012-02-17 18:41:24