比较qt中的字符串并不起作用

时间:2016-04-25 08:17:39

标签: c++ qt

我试图在Qt中将两个字符串与默认值进行比较但总是失败。它始终是假的

如果group == default,则转到s.beginGroup,但该组名为Default。我不知道问题出在哪里,这太奇怪了。

 foreach (const QString &group, s.childGroups()) {
        if(group =="Default")
            continue;
        s.beginGroup(group);
        Profile *profile = new Profile();
        profile->setObjectName(group);
        profile->load(s);
        s.endGroup();

        m_Profiles << profile;

    }

3 个答案:

答案 0 :(得分:1)

如果编译器启用了C ++ 11,则最好切换到ranged-for:

for (const QString& group : s.childGroups())
{ ... }

Ranged-for循环按预期支持continue个关键字

此外,必须将CONFIG += c++11添加到项目的* .pro文件中

答案 1 :(得分:0)

Qt中foreach的定义解析如下:

#  define Q_FOREACH(variable, container)                                \
for (QForeachContainer<QT_FOREACH_DECLTYPE(container)>  _container_((container)); \
 _container_.control && _container_.i != _container_.e;         \
 ++_container_.i, _container_.control ^= 1)                     \
    for (variable = *_container_.i; _container_.control; _container_.control = 0)

因为您可以看到有两个for循环,可能continue关键字不会继续您想要的那个,而是内部的。

@ chi的评论后

编辑

Qt头文件中有一个很好的解释:

// Explanation of the control word:
//  - it's initialized to 1
//  - that means both the inner and outer loops start
//  - if there were no breaks, at the end of the inner loop, it's set to 0, which
//    causes it to exit (the inner loop is run exactly once)
//  - at the end of the outer loop, it's inverted, so it becomes 1 again, allowing
//    the outer loop to continue executing
//  - if there was a break inside the inner loop, it will exit with control still
//    set to 1; in that case, the outer loop will invert it to 0 and will exit too

正如您所看到的那样,只有休息时间没有提及continue。并且continue文档页面上没有提及foreachhttp://doc.qt.io/qt-4.8/containers.html#the-foreach-keyword仅显示中断。

答案 2 :(得分:0)

适合我:

#include <QtCore>

int main() {
   auto const kDefault = QStringLiteral("Default");
   QStringList groups{"a", kDefault, "b"};
   QStringList output;
   // C++11
   for (auto group : groups) {
      if(group == kDefault)
         continue;
      Q_ASSERT(group != kDefault);
      output << group;
   }
   // C++98
   foreach (const QString &group, groups) {
      if(group == kDefault)
         continue;
      Q_ASSERT(group != kDefault);
      output << group;
   }
   Q_ASSERT(output == (QStringList{"a", "b", "a", "b"}));
}

您的问题出在其他地方,或者您的调试器对您撒谎。