QT,C ,没有对象,无法调用成员功能

QT, C++, cannot call member function without object

本文关键字:调用 功能 成员 对象 QT      更新时间:2023-10-16

在我的mainwindow.cpp中是呼叫的位置。应该在按钮点击事件上发生呼叫。错误说cannot call member function 'void Foo::setFooAttributes(A&, B&, C&, D&)' without object

void MainWindow::on_generateButton_clicked()
{
  setCreator(ui->interfaceCreatorName->text());
  setAlternateName(ui->interfaceAlternateName->text());
  setDomain(ui->interfaceDomain->text().toInt());
  QString filename = getCreator() + "'s " + getAlternateName() + ".txt";
  QFile file( filename );
  A a; B b; C c; D d;
  Foo::setFooAttributes(a,b,c,d); //ERROR: cannot call member function without object
  generateTop(file);
  generateMiddle(file);
  generateSecondaryMid(file);
  generateLast(file);
  generateTertiaryMid(file, a, b, c, d);
}

功能本身看起来像这样:

void Foo::setFooAttributes(A &aFoo, B &bFoo, C &cFoo, D &dFoo){
   aFoo.stopPoint = MainWindow.ui->aInterfaceStopPoint->text().toDouble();
   aFoo.rate = MainWindow.ui->aInterfaceRate->text().toInt();
   aFoo.domain = MainWindow.ui->aInterfaceDomain->text().toInt();
   aFoo.length = MainWindow.ui->aInterfaceLength->text().toInt();
   bFoo.stopPoint = MainWindow.ui->bInterfaceStopPoint->text().toDouble();
   bFoo.rate = MainWindow.ui->bInterfaceRate->text().toInt();
   bFoo.domain = MainWindow.ui->bInterfaceDomain->text().toInt();
   bFoo.length = MainWindow.ui->bInterfaceLength->text().toInt();
   cFoo.stopPoint = MainWindow.ui->cInterfaceStopPoint->text().toDouble();
   cFoo.rate = MainWindow.ui->cInterfaceRate->text().toInt();
   cFoo.domain = MainWindow.ui->cInterfaceDomain->text().toInt();
   cFoo.length = MainWindow.ui->cInterfaceLength->text().toInt();
   dFoo.stopPoint = MainWindow.ui->dInterfaceStopPoint->text().toDouble();
   dFoo.rate = MainWindow.ui->dInterfaceRate->text().toInt();
   dFoo.domain = MainWindow.ui->dInterfaceDomain->text().toInt();
   dFoo.length = MainWindow.ui->dInterfaceLength->text().toInt();
}

我将其余的代码放在粘贴中,包括foo.h,pastebin source

我首先尝试在没有Foo::的情况下调用setFooAttributes(a,b,c,d);,但这给了我错误,例如'setFooAttributes' was not declared in this scope

使您的 Foo::setFooAttributes成为 static成员函数,因为它无法在"这个"实例上操作。

当您使用时,如果A/B/C/D实际上是相同的类型(或普通类型的亚型),则可以考虑删除所有重复,以更好地遵循干燥(不要重复自己)原理:

template <typename A> static void Foo::setFooAttributes(Foo &aFoo, int iface) {
   aFoo.stopPoint = MainWindow.ui->interfaceStopPoint[iface]->text().toDouble();
   aFoo.rate = MainWindow.ui->interfaceRate[iface]->text().toInt();
   aFoo.domain = MainWindow.ui->interfaceDomain[iface]->text().toInt();
   aFoo.length = MainWindow.ui->interfaceLength[iface]->text().toInt();
}
static void Foo::setFooAttributes(Foo &aFoo, Foo &bFoo, Foo &cFoo, Foo &dFoo) {
    setFooAttributes(aFoo, 0);
    setFooAttributes(bFoo, 1);
    setFooAttributes(cFoo, 2);
    setFooAttributes(dFoo, 3);
}

(这需要您将{a,b,c,d}InterfaceStopPoint{a,b,c,d}InterfaceRate{a,b,c,d}InterfaceDomain{a,b,c,d}InterfaceLength的每个变量转换为数组,而不是四个单独的变量)。

您甚至可以通过使用循环或可变的模板功能来改进此功能,但我将其作为练习。