2016-04-25 87 views
-1

我想比较两个字符串与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; 

    } 

回答

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循环,可能是继续关键字不跟你想的一个继续,但内在的一个。

编辑 @驰的评论

有一个在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只有突破提及。并且在foreach文档页面上没有提及continuehttp://doc.qt.io/qt-4.8/containers.html#the-foreach-keyword仅提供了中断。

+0

哇。 “_container_.control”的基础逻辑很有趣。 – chi

+0

无论如何,'continue'或'break'都会退出当前块,所以它不能解决原来的问题。它不会去's.beginGroup'! –

+0

'continue'和'break'在'Q_FOREACH'内正常工作。也许他们已经破坏了可憎的事情,那就是在VC6上运行的实现,但是其他一切都已经破坏了,所以我们不要详谈。 –

1

如果编译器是C++ 11使你更好地切换到远程换代替:

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

远程-for循环支持continue关键字如预期

此外,CONFIG += c++11必须加入到*你对我的项目

0

工程的.pro文件:

#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"})); 
} 

你的问题在其他地方,或者你的调试器对你说谎。