我遇到了指向const QList of pointers to Foo
的指针。我将myListOfFoo
对象的Bar
指针传递给Qux
。我使用指向const的指针来防止在Bar
类之外进行任何更改。问题是,我仍然可以修改ID_
中执行setID
的{{1}}。
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();
}
我想要实现的目标是:
-1
100
使用-1
no change
-1
代替QList<Foo>
时没有这样的问题,但我需要在代码中使用QList<Foo*>
。
感谢您的帮助。
答案 0 :(得分:1)
应该是:
QList<const Foo *>* listOfFoo;
答案 1 :(得分:1)
您可以使用QList<Foo const *> const *
,这意味着您不能修改列表或列表内容。问题是没有简单的方法可以从QList<Foo*>
检索该列表,因此您需要将其添加到Bar
类中。
答案 2 :(得分:0)
如果你真的必须返回指针,将其强制转换为包含指向常量元素的指针的QList:
QList<const Foo*> const* getMyListOfFoo()
{return reinterpret_cast<QList<const Foo*> *>(myListOfFoo_);};
在Qux listOfFoo中也应该包含指向常量元素的指针:
QList<const Foo*> const* listOfFoo;