2

假设我有以下代码(C++/Qt):

QHash<QString, AppInfo*> links;
QList<AppInfo> apps = m_apps.values();
for (const AppInfo &app : apps) {
    // Doing something with #app variable...
    links.insert(app.other._appFile, &app);
}

m_appsis QHash<QString, AppInfo>,并且app.other._appFile是文件的完整路径。

&app问题来了:倒数第二行的构造是否正确?我需要一个指向 AppInfo 对象的非常量指针,以便稍后对其进行修改。是否直接&app链接到const AppInfo&AppInfo对象?如果我尝试修改获得的AppInfo*对象,应用程序不会崩溃吗?谢谢你。

抱歉,英语不是我的母语,我无法完美地制定问题标题。请代替我做。

4

1 回答 1

2

linksQHash<QString, AppInfo*>,不是QHash<QString, const AppInfo*>,因此由

links.insert(app.other._appFile, &app);

您正在启动隐式转换const AppInfo*AppInfo* 将导致编译器错误,而不是运行时错误(崩溃)。一个明显的解决方案是在没有 const 的情况下遍历地图

for (AppInfo &app : apps) 
{

}
于 2013-06-12T15:50:22.067 回答