0

constへのポインタでスタックしましたQList of pointers to Foo。オブジェクトからにmyListOfFooポインタを渡します。クラス外での変更を防ぐために、constへのポインターを使用します。問題は、での実行を変更できることです。BarQuxBarID_setIDQux::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*>

手伝ってくれてありがとう。

4

3 に答える 3

1

次のようにする必要があります。

QList<const Foo *>* listOfFoo;
于 2010-10-12T13:18:42.747 に答える
1

QList<Foo const *> const *リストまたはリストの内容を変更できないことを意味する a を使用できます。問題は、そのリストを から取得する簡単な方法がないため、クラスQList<Foo*>に追加する必要があることです。Bar

于 2010-10-12T13:19:29.893 に答える
0

本当にポインターを返す必要がある場合は、定数要素へのポインターを含む QList にキャストします。

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

Qux listOfFoo では、定数要素へのポインタも含める必要があります。

QList<const Foo*> const* listOfFoo;
于 2010-10-15T09:05:17.483 に答える