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

hak*_*ami 1 c++ qt qt4

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

我有这个自定义的结构

struct oneRectangle
{
    QString partName;
    QGraphicsRectItem * rectangle;
};
Run Code Online (Sandbox Code Playgroud)

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

QList<oneRectangle> partList;
Run Code Online (Sandbox Code Playgroud)

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

partList.at(index).rectangle = some pointer points to a QGraphicsRectItem
Run Code Online (Sandbox Code Playgroud)

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

lee*_*mes 13

更改

partList.at(index).rectangle
Run Code Online (Sandbox Code Playgroud)

partList[index].rectangle
Run Code Online (Sandbox Code Playgroud)

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

  • `QList :: at`的行为与`std :: vector :: at`不同.请参阅QVector的文档(在我的回答中链接). (3认同)