我创建了许多“问题”对象并将它们存储在向量中。我想遍历向量,并在对象包含某个功能的情况下在索引处执行某些操作。这些是我所拥有的东西,有些对象的布置会有所不同。
QLabel *titleLabel;
QTextEdit *textEdit;
QLineEdit *lineEdit;
QLabel *commentsLabel;
QTextEdit *commentsEdit;
QLineEdit *option;
QLabel *scaleLabel;
QLabel *label;
QLineEdit *scaleFrom;
QLineEdit *scaleTo;
如果索引处的对象没有特定的东西,我的代码将崩溃。
问题*问题;
for(int i = 0; i< question_vector.size(); i++){
question = question_vector[i];
if(question->scaleFrom)
{
qDebug() << question->scaleFrom->text();
}
else
{
qDebug() << "no";
}
}
索引为0的对象没有'scaleFrom',因此我的程序崩溃了。我该如何处理并跳过呢?
您正在取消引用指针。它需要指向一个有效的内存地址。如果您的对象没有东西,可以将其指针设置为NULL或nullptr(C ++ 11),这样就可以检查它们是否==为null。然后可以在取消引用指针之前检查指针是否为null。
代替
qDebug() << question->scaleFrom->text();
您将拥有:
if (question != nullptr && question->scaleFrom != nullptr)
qDebug() << question->scaleFrom->text();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句