gpt4 book ai didi

c++ - QMetaObject 在指针列表中查找类名

转载 作者:行者123 更新时间:2023-11-30 05:38:28 25 4
gpt4 key购买 nike

我有一个 RegistrationList 类,它有一个函数,该函数应该遍历注册指针列表,然后返回传递给该函数的特定注册类型的总费用作为 QString。当我从我的 gui 实现类调用此函数时,它总是返回 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);
}
}

最佳答案

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

提示:您的 classNamet 的比较并不像您认为的那样。您正在比较指针,而您应该在其中比较字符串。将测试重写为以下之一:

  1. QString::fromLatin1(attendeeList.at(i)->metaObject()->className()) == t,或

  2. !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[] 会做你想做的事。您还应该通过引用传递不需要拷贝的字符串,而不是值。使用迭代器可以让您完全摆脱显式索引:

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;
}

如果您的编译器支持 range-for,您应该改用它。现在已经不是 00 年代了。

double RegistrationList::totalFees(const QString & t) const {
double total = 0.00;
for (auto attendee : attendeeList)
if (attendee->is(t)) total += attendee->calculateFee();
return total;
}

如果您愿意,您也可以使用 std::accumulate(参见 this answer):

double RegistrationList::totalFees(const QString & t) const {
return std::accumulate(attendeeList.begin(), attendeeList.end(), 0.0,
[t](Registration* attendee) -> double {
return attendee->is(t) ? attendee->calculateFee() : 0.0;
});
}

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

关于c++ - QMetaObject 在指针列表中查找类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32759197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com