constへのポインタでスタックしましたQList of pointers to Foo
。オブジェクトからにmyListOfFoo
ポインタを渡します。クラス外での変更を防ぐために、constへのポインターを使用します。問題は、での実行を変更できることです。Bar
Qux
Bar
ID_
setID
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*>
使用する必要があります。QList<Foo*>
手伝ってくれてありがとう。