2010-10-12 68 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