【发布时间】:2010-10-12 12:50:22
【问题描述】:
我被指向 const QList of pointers to Foo 的指针卡住了。我将指向myListOfFoo 的指针从Bar 对象传递给Qux。我使用指向 const 的指针来防止在 Bar 类之外进行任何更改。问题是我仍然可以修改ID_ 在Qux::test() 中执行setID。
#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*>。
感谢您的帮助。
【问题讨论】:
-
QList
const* - 不要在堆上创建 Qt 容器,它们是隐式共享的(写时复制)。只需通过 value/const 引用传递它们。 -
@Frank 感谢您的建议,但您能否详细说明如何操作。恐怕我的编程能力不够强,无法理解你的想法:)。
-
如果你想从你的内部 QList
中获得一个 QList ,你所能做的就是创建一个新列表并手动附加指针。 QList list() const { QList cl; /* 循环/追加... */ return cl; }。或者保留多个列表。 -
@Moomin:使成员成为普通的 QList
和 QList getMyListOfFoo() const 如上所述返回一个副本(我使用了 list())。那么外面没有人可以直接修改列表(因为他将在副本上操作),但这似乎是你想要的吗? -
@Frank 我想就是这样,但我希望不必复制整个列表 - 它计划很长,因此它可能是非常消耗内存的解决方案。
标签: c++ qt qt4 const-correctness pointer-to-member