2010-10-12 29 views
0

我被指向常量QList of pointers to Foo的指針卡住了。我將指針從Bar對象傳遞到myListOfFooQux。我使用const指針來防止在Bar類之外進行任何更改。問題是我仍然可以修改ID_執行setIDQux::test()Qt4 C++指向常量Q指針的列表

#include <QtCore/QCoreApplication> 
#include <QList> 
#include <iostream> 

using namespace std; 

class Foo 
{ 
private: 
    int  ID_; 
public: 
    Foo(){ID_ = -1; }; 
    void setID(int ID) {ID_ = ID; }; 
    int getID() const {return ID_; }; 
    void setID(int ID) const {cout << "no change" << endl; }; 
}; 

class Bar 
{ 
private: 
    QList<Foo*> *myListOfFoo_; 
public: 
    Bar(); 
    QList<Foo*> const * getMyListOfFoo() {return myListOfFoo_;}; 
}; 

Bar::Bar() 
{ 
    this->myListOfFoo_ = new QList<Foo*>; 
    this->myListOfFoo_->append(new Foo); 
} 

class Qux 
{ 
private: 
    Bar *myBar_; 
    QList<Foo*> const* listOfFoo; 
public: 
    Qux() {myBar_ = new Bar;}; 
    void test(); 
}; 

void Qux::test() 
{ 
    this->listOfFoo = this->myBar_->getMyListOfFoo(); 
    cout << this->listOfFoo->last()->getID() << endl; 
    this->listOfFoo->last()->setID(100); //   **<---- MY PROBLEM** 
    cout << this->listOfFoo->last()->getID() << endl; 
} 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 

    Qux myQux; 
    myQux.test(); 

    return a.exec(); 
} 

結果的上面的代碼是:

-1 
100 

和我想要實現的是:

-1 
no change 
-1 

有沒有這樣的問題,當我使用QList<Foo>代替QList<Foo*>但我需要在我的代碼中使用QList<Foo*>

感謝您的幫助。

+1

的QList 常量* - 不要在堆上創建Qt容器,它們會被共享(寫時複製)。只需通過值/ const引用傳遞它們即可。 – 2010-10-12 13:47:06

+0

@Frank謝謝你的建議,但是你能否詳細說明一下如何去做。恐怕我的編程技能不夠強大,無法理解你的想法:)。 – Moomin 2010-10-12 13:51:17

+1

如果你想從你的內部QList QList ,你所能做的就是創建一個新的列表並手動添加指針。 QList list()const {QList cl;/* loop/append ... */return cl; }。或保留多個列表。 – 2010-10-12 13:52:08

回答

1

應該是:

QList<const Foo *>* listOfFoo; 
+0

如果我這樣做,我需要在其他行中將'QList *'更改爲'QList *'以避免編譯錯誤:無法在分配中將'const QList *'轉換爲'const QList *'。但是,我不能從任何地方執行setID(e.q.Bar :: Bar()) – Moomin 2010-10-12 13:29:37

+1

yes,you can;) const_cast (this-> listOfFoo-> last()) - > setID(100); – noisy 2010-10-12 18:41:49

1

你可以使用一個QList<Foo const *> const *,這意味着你不能修改列表或列表的內容。問題是沒有簡單的方法從QList<Foo*>中檢索該列表,因此您需要將其添加到Bar類中。

0

如果你真的有返回指針,將其轉換爲包含的QList指針常量元素:

QList<const Foo*> const* getMyListOfFoo() 
{return reinterpret_cast<QList<const Foo*> *>(myListOfFoo_);}; 

在Qux listOfFoo應包含指向常量元素太:

QList<const Foo*> const* listOfFoo; 
+0

實際上,我認爲您的解決方案可能有問題,因爲輸入「QList const * getMyListOfFoo(){return reinterpret_cast *>(myListOfFoo_);}」結果沒有變化 - 仍爲-1和100 – Moomin 2010-10-15 17:39:13

+0

如果您可以用更多的細節來解釋你的想法,也許我會理解它。提前致謝。 – Moomin 2010-10-15 17:44:49

+0

對於遲到的響應和一些格式錯誤感到抱歉。現在它應該工作。這個想法是,列表中的元素應該如10月12日13:52在Frank所建議的那樣不變。 Reinterprete_cast可幫助您將課堂內使用的QList 轉換爲QList 供外部使用。 – 2010-10-18 18:17:59