我创建了许多“问题”对象并将它们存储在一个 vector 中。 如果对象包含某个特征,我想遍历 vector 并在索引处做一些事情。这些是我拥有的东西,有些对象会有不同的排列方式。
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。然后,您可以在取消引用之前检查指针是否为空。
代替
qDebug() << question->scaleFrom->text();
你会:
if (question != nullptr && question->scaleFrom != nullptr)
qDebug() << question->scaleFrom->text();
关于c++ - 通过 vector 中对象的各个方面处理崩溃循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212763/