QMetaObject在指针列表中查找类名

时间:2015-09-24 10:36:19

标签: c++ qt

我有一个RegistrationList类,它具有一个函数,该函数应该在一个Registration指针列表中进行迭代,然后返回作为QString传递给该函数的特定注册类型的总费用。当我从我的gui implimentation类调用这个函数时,它总是返回0,即使我可以看到注册列表类中有注册指针。知道我做错了什么吗?我猜这与我使用QMetaObject有关但不确定。下面的第一个函数是RegistrationList函数,第二个函数是我的gui类中的插槽。

我的代码:

double RegistrationList::totalFees(QString t) {
    double total = 0.00;
        for (int i = 0; i < attendeeList.size(); ++i) {
        if (attendeeList.at(i)->metaObject()->className() == t)
            total += attendeeList.at(i)->calculateFee();
    }


void MainWindow::totalFees_clicked() {
  if (ui->rdbGuest->isChecked()) {
      double total = m_rList.totalFees("GuestRegistration");
      QMessageBox::information(this, "Total guest registration fees", QString("Total guest registration fees: R    %1").arg(total), QMessageBox::Ok);
  }
  else if(ui->rdbStandard->isChecked()) {
      double total = m_rList.totalFees("StandardRegistration");
      QMessageBox::information(this, "Total standard registration fees", QString("Total standard registration     fees: R%1").arg(total), QMessageBox::Ok);
  }
  else if (ui->rdbStudent->isChecked()) {
      double total = m_rList.totalFees("StudentRegistration");
      QMessageBox::information(this, "Total student registration fees", QString("Total student registration     fees: R%1").arg(total), QMessageBox::Ok);
  }
}

1 个答案:

答案 0 :(得分:1)

DEFINES += QT_NO_CAST_FROM_ASCII QT_NO_CAST_TO_ASCII添加到项目文件中,重新编译代码并修复所有错误。

提示:您与className的{​​{1}}比较与您认为的不相符。您正在比较指针,您应该在哪里比较字符串。将测试重写为以下之一:

  1. t

  2. QString::fromLatin1(attendeeList.at(i)->metaObject()->className()) == t

  3. 此操作应该是!strcmp(attendeeList.at(i)->metaObject()->className(), t.toLatin1())类的成员(如果Registration包含attendeeList类型的值):

    Registration*

    您的class Registration : public QObject { ... public: bool is(const QString & className) const { return QString::fromLatin1(metaObject()->className()) == t; } ... }; 应该是totalFees方法,然后您不需要所有const详细程度:at()将按照您的意愿行事,然后。您还应该传递不需要参考的字符串,而不是值。使用迭代器可以完全摆脱显式索引:

    operator[]

    如果你的编译器支持range-for,你应该使用它。它不再是&00; 00了。

    double RegistrationList::totalFees(const QString & t) const {
      double total = 0.0;
      for (auto it = attendeeList.begin(); it != attendeeList.end(); ++it)
        if ((*it)->is(t)) total += (*it)->calculateFee();
      return total;
    }
    

    如果您愿意,也可以使用double RegistrationList::totalFees(const QString & t) const { double total = 0.00; for (auto attendee : attendeeList) if (attendee->is(t)) total += attendee->calculateFee(); return total; } (请参阅this answer):

    std::accumulate

    最后,你永远不应该使用浮点类型来处理钱。使用适当的类来包装整数类型以表示您希望处理的最低货币单位。