2016-04-25 85 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"})); 
} 

你的問題在其他地方,或者你的調試器對你說謊。