通过向量中对象的各个方面处理崩溃循环

Handle crash looping through aspects of object in vector

我创建了许多 'question' 个对象并将它们存储在一个向量中。 如果对象包含某个特征,我想遍历向量并在索引处做一些事情。这些是我有的东西,有些对象会有不同的排列方式。

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();