有一个名为m_noteList
的QList 成员变量,其中包含类Note
的QSharedPointer 元素。
private:
QList< QSharedPointer<Note> > m_noteList;
如果创建了一个新笔记,它的引用将附加到列表中:
void Traymenu::newNote(){
QSharedPointer<Note> note(new Note(this));
m_noteList << note;
}
对于每个音符元素,其指针位于 m_noteList 中,我想获取其标题并将其添加到我的上下文菜单中。目的是单击该标题以打开注释:
for ( int i = 0 ; i < m_noteList.count() ; i++ ) {
std::string menuEntryName = m_noteList[i].getTitle();
QAction *openNote = m_mainContextMenu.addAction(menuEntryName);
}
我得到一个错误
C:\project\traymenu.cpp:43: Fehler: 'class QSharedPointer<Note>' has no member named 'getTitle'
std::string menuEntryName = &m_noteList[i].getTitle();
^
基本上,我想访问 m_noteList
中引用的对象。我怎么做?我想使用 m_noteList[i]
来访问该元素,但显然编译器需要 QSharedPointer
类型的东西。为什么?
最佳答案
QSharedPointer
基本上包裹了您的指针。所以你不能直接用'.'访问。运算符,这就是您收到此错误的原因:getTitle
不是类 QSharedPointer
的一部分。
但是你有多种方法来检索实际指针:
data
:不是最简单的方法,但它是明确的,有时很重要operator->
:这样您就可以像使用实际指针一样使用您的QSharedPointer
m_noteList[i]->getTitle();
<operator*
:做类似(*m_noteList[i]).getTitle();
的事情
关于c++ - 访问 QList 和 QSharedPointer 中引用的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21968575/