只读结构?如何在结构中使用指针?

时间:2012-07-30 12:46:04

标签: c++ qt qt4

我对这个问题感到很疯狂。

我有这个自定义结构

struct oneRectangle
{
    QString partName;
    QGraphicsRectItem * rectangle;
};

我有一个List使用这个结构作为模板:

QList<oneRectangle> partList;

在我追加struct的实体(没有init指针)之后,我需要做这样的事情:

partList.at(index).rectangle = some pointer points to a QGraphicsRectItem

但是,我得到一个错误,说结构是一个只读结构。我首先尝试malloc指针,然后将其附加到列表中,但是当我为指针分配地址时,我仍然得到错误。 这有什么问题?

2 个答案:

答案 0 :(得分:13)

更改

partList.at(index).rectangle

partList[index].rectangle

as QList::operator[](int)返回一个可修改的引用,其中QList::at(int)返回一个const引用(因此不可修改)。

答案 1 :(得分:0)

重点是:使用something.at(index)进行显示,使用[index]进行编辑。为什么不为两者使用[]?因为我已经在某处读过“.at()”更有效,更快。我没试过它......