-
switch(id) {
-
case 0:
-
break;
-
case 1:
-
break;
-
case 2:
-
-
m_rdpDialog = new rdpDialog();
-
m_rdpDialog->setModal(true);
-
this->m_rdp.append(m_rdpDialog);
-
-
QString userName("rdp_");
-
userName += QString::number(qrand() % 1000);
-
m_rdpDialog->setString(userName);
-
-
QStringList userInfo;
-
userInfo << "RDP";
-
userInfo.append(userName);
-
userInfo << "192.168.2.100" << "auto";
-
this->slotAddContect(userInfo);
-
-
m_rdpDialog->show();
-
break;
-
-
case 3:
-
break;
-
default:
-
break;
-
}
编译出错信息:
p, li { white-space: pre-wrap; }
loginWidget.cpp: In member function ‘void loginWidget::slotBtnClicked(int)’:
loginWidget.cpp:242: error: jump to case label
loginWidget.cpp:233: error: crosses initialization of ‘QStringList userInfo’
loginWidget.cpp:229: error: crosses initialization of ‘QString userName’
loginWidget.cpp:244: error: jump to case label
loginWidget.cpp:233: error: crosses initialization of ‘QStringList userInfo’
loginWidget.cpp:229: error: crosses initialization of ‘QString userName’
make: *** [loginWidget.o] Error 1
make: Leaving directory `/home/step_by_step/qt_exercise/login'
Exited with code 2.
Error while building project login
When executing build step 'Make'
原因是因为在C和C++中,一个变量的生命期(作用域)问题
这里的userInfo ,userName 的生命期为从 QString username, QStringList 开始到 switch 的 }结束
也就是说在 case 2 之后的 case 3 , default 中仍能访问 username ,useInfo .
考虑这样一种情况,如果switch匹配了case 3,这样case 2的代码被跳过了,那么username, userInfo就没有定义,如果此时在case 3的代码中访问了username, userInfo,程序会崩溃的。
所以上面的程序应写成如下方式
-
switch(id) {
-
case 0:
-
break;
-
case 1:
-
break;
-
case 2:
-
{
-
m_rdpDialog = new rdpDialog();
-
m_rdpDialog->setModal(true);
-
this->m_rdp.append(m_rdpDialog);
-
-
QString userName("rdp_");
-
userName += QString::number(qrand() % 1000);
-
m_rdpDialog->setString(userName);
-
-
QStringList userInfo;
-
userInfo << "RDP";
-
userInfo.append(userName);
-
userInfo << "192.168.2.100" << "auto";
-
this->slotAddContect(userInfo);
-
-
m_rdpDialog->show();
-
break;
-
}
-
case 3:
-
break;
-
default:
-
break;
-
}
参考链接:
http://zhubangbing.blog.163.com/blog/static/526092702011931821900/
阅读(3767) | 评论(0) | 转发(0) |