2012-07-31 151 views
1

我不斷收到此錯誤:Qt的C++不能調用成員函數「」沒有對象

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

現在即時通訊相當新的C++和Qt所以我不會知道這意味着什麼。我正在嘗試從另一個類中調用一個函數來設置一些lcdNumber上的數字。這裏是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; 
} 

這裏是Load.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 

最後的地方,我調用該函數:

​​

當我運行這個我得到那個錯誤。林不知道這意味着什麼,如果任何人都可以幫助我會感謝。謝謝。

回答

7

錯誤說明是很清楚

不能調用成員函數「QString的負載:: loadRoundsPlayed()」沒有對象

你不能調用成員函數,那不是靜態的,而無需創建實例班上。在你的代碼


看,你可能需要做:

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

還有其他兩個選項:

  • 使loadRoundsPlayed靜態和靜態roundsPlayed,如果你不希望它們與具體實例相關聯或
  • 使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; 
} 
1

因爲方法和成員不與類的實例相關聯,使之靜:

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

如果你希望他們與實例相關聯,你需要創建一個對象並調用它的方法(在這種情況下,它不一定是static)。

0

Load::loadRoundsPlayed(),你應該改變

Load::roundsPlayed = roundsFile.readAll(); 

this->roundsPlayed = roundsFile.readAll(); 

或者乾脆

roundsPlayed = roundsFile.readAll(); 

這個特殊的例子並不能修復編譯器錯誤,但它說明你在哪裏對語法有一些困惑。當你用「Load ::」作爲函數或變量名的前綴時,你說你想要屬於這個類的字段。但是,類的每個對象都將擁有自己的已聲明變量的副本。這意味着你需要創建一個對象,然後才能使用它們。同樣,函數綁定到對象,所以你需要一個對象來調用成員函數。

另一種選擇是使你的功能static,使你不需要一個對象來調用它。我強烈建議您瞭解實例函數和類的靜態函數之間的區別,以便在情況需要時適當地使用這兩種工具。

相關問題