开发者

Qt4 C++ Pointer to const QList of pointers

I got stuck with pointer to const QList of pointers to Foo. I pass pointer to myListOfFoo from Bar object to Qux. I use pointer to const to prevent making any changes outside Bar class. The problem is that I'm still able to modify ID_ executing setID in Qux::test().

#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();
}

Result of above code is:

-1
100

and what I'm trying to achieve is:

-1
no change
-1

There is no such problem when I use QList<Foo> instead开发者_JAVA技巧 of QList<Foo*> but I need to use QList<Foo*> in my code.

Thanks for help.


should be:

QList<const Foo *>* listOfFoo;


You could use a QList<Foo const *> const * which means you are not allowed to modify the list or the content of the list. The problem is that there is no easy way to retrieve that list from a QList<Foo*>, so you need to add it in your Bar class.


If you really have to return pointer, cast it to QList containing pointers to constant elements:

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

In Qux listOfFoo should contain pointers to constant elements too:

QList<const Foo*> const* listOfFoo;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜