Qt C++ 不能在没有对象的情况下调用成员函数

Qt C++ cannot call member function ' ' without object

本文关键字:情况下 调用 成员 函数 对象 C++ 不能 Qt      更新时间:2023-10-16

我一直收到这个错误:

cannot call member function 'QString Load::loadRoundsPlayed()'without object

现在我对c++和qt还很陌生,所以我不确定这意味着什么。我正试图从另一个类调用一个函数来设置一些lcdNumbers上的数字。这是Load.cpp,它包含以下功能:

#include "load.h"
#include <QtCore>
#include <QFile>
#include <QDebug>
Load::Load() //here and down
{}
QString Load::loadRoundsPlayed()
{
    QFile roundsFile(":/StartupFiles/average_rounds.dat");
    if(!roundsFile.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug("Could not open average_rounds for reading");
    }
    Load::roundsPlayed = roundsFile.readAll();
    roundsFile.close();
    return Load::roundsPlayed;
}

这是负载。h:

    #ifndef LOAD_H
     #define LOAD_H
    #include <QtCore>
    class Load
    {
    private:
        QString roundsPlayed; //and here
    public:
        Load();
        QString loadRoundsPlayed(); //and here
    };
    #endif // LOAD_H

最后是我调用函数的地方:

    #include "mainwindow.h"
     #include "ui_mainwindow.h"
    #include "load.h"
    #include <QLCDNumber>
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        MainWindow::startupLoad();
    }
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    void MainWindow::startupLoad()
    {
        ui->roundPlayer_lcdNumber->display(Load::loadRoundsPlayed()); //right here
    }

当我运行这个时,我会得到那个错误。我不知道这意味着什么,所以如果有人能帮助我,我将不胜感激。谢谢

错误描述非常清楚

无法在没有对象的情况下调用成员函数'QString-Load::loadRoundsPlayed()'

如果不创建类的实例,就不能调用非静态的成员函数。


看看你的代码,你可能需要这样做:

Load load;
ui->roundPlayer_lcdNumber->display(load.loadRoundsPlayed()); //right here

还有另外两种选择:

  • 如果不希望loadRoundsPlayedroundsPlayed与具体实例关联,请将它们设置为static或
  • 使loadRoundsPlayed为静态,并通过复制返回QString,这将在函数内部本地创建。类似于

QString Load::loadRoundsPlayed()
{
    QFile roundsFile(":/StartupFiles/average_rounds.dat");
    if(!roundsFile.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug("Could not open average_rounds for reading");
    }
    QString lRoundsPlayed = roundsFile.readAll();
    roundsFile.close();
    return lRoundsPlayed;
}

因为方法和成员与类实例不关联,所以将其设为静态:

class Load
{
private:
    static QString roundsPlayed;
public:
    Load();
    static QString loadRoundsPlayed();
};

如果希望它们与实例相关联,则需要创建一个对象并调用该对象上的方法(在这种情况下不必是static)。

Load::loadRoundsPlayed()中,您应该更改

Load::roundsPlayed = roundsFile.readAll();

this->roundsPlayed = roundsFile.readAll();  

或简称

roundsPlayed = roundsFile.readAll();

这个特殊的例子不会修复编译器错误,但它说明了您在语法方面的一些困惑。当您在函数或变量名前面加上"Load::"时,表示您想要属于此类的字段。然而,类的每个对象都有自己的变量副本,这意味着在使用它们之前,您需要创建一个对象。类似地,函数绑定到对象,因此您再次需要一个对象来调用成员函数。

另一种选择是将函数设为static,这样就不需要对象来调用它。我强烈建议您了解类的实例函数和静态函数之间的区别,以便在需要时可以适当地使用这两种工具。