"Undefined reference to"

"Undefined reference to"

本文关键字:to Undefined reference      更新时间:2023-10-16

我知道有很多问题与此有关,但它们的答案对我来说有点难以理解。对于几行不同的代码,我收到以下错误:

C:UsersJeffAppDataLocalTempccAixtmT.o:football.cpp:(.text+0x6f0): undefined 
reference to `Player::set_values(int, std::string, float)'

从这些代码块:

class Player {
int playerNum;
string playerPos;
float playerRank;
public:
    void set_values(int, string, float);
    float get_rank(){ return playerRank; };
    bool operator == (const Player &p1/*, const Player &p2*/) const
    {
    if(&p1.playerNum == &playerNum &&
       &p1.playerPos == &playerPos &&
       &p1.playerRank == &playerRank)
       return true;
    else
       return false; };
};

这是引用子类的主要函数:

int main() {
ifstream infile;
infile.open ("input.txt", ifstream::in);
int numTeams;
string command;
while(!infile.fail() && !infile.eof()){
    infile >> numTeams;
    string name;
    Player p;
    int playNum;
    string playPos;
    float playRank;
    Player all[11];
    float ranks[11];
    Team allTeams[numTeams];
    for(int i=0; i<numTeams; i++){
        infile >> name;
        for(int j=0; j<11; j++){
            infile >> playNum;
            infile >> playPos;
            infile >> playRank;
            if(playPos == "QB")
                p.set_values(playNum, playPos, (playRank*2.0));
            else if(playPos == "RB")
                p.set_values(playNum, playPos, (playRank*1.5));
            else if(playPos == "WR")
                p.set_values(playNum, playPos, (playRank/1.8));
            else if(playPos == "TE")
                p.set_values(playNum, playPos, (playRank*1.1));
            else if(playPos == "GD")
                p.set_values(playNum, playPos, (playRank/2.0));
            else if(playPos == "TC")
                p.set_values(playNum, playPos, (playRank/2.2));
            else if(playPos == "CR")
                p.set_values(playNum, playPos, (playRank/1.2));
            all[j] = p;
            allTeams[i].set_values(all, name);
        }
    }
    infile >> command;
    if (command == "play"){ 
        int t1;
        int t2;
        infile >> t1;
        infile >> t2;
        play(allTeams[t1], allTeams[t2]); 
    }
    else { 
        int t1;
        int p1;
        int t2;
        int p2;
        swap(allTeams[t1], allTeams[t1].get_player(p1), allTeams[t2], allTeams[t2].get_player(p2)); }
}
}

你在类中声明了set_values,但从未像其他人那样为它提供正文。调用函数时,无需执行任何内容!

好吧,这里有几个错误,但关于你的问题,这是应该如何实现set_value:

 void set_values(int playerNumParam, string playerPosParam, float playerRankParam){
     playerNum = playerNumParam;
     playerPos = playerPosParam;
     playerRank = playerRankParam;
}

请参阅此链接:构造函数和析构函数

此外,为了良好实践,最好通过以下划线结尾来命名类成员变量

playerNum_
playerPos_
playerRank_

希望它有帮助!

找不到函数的几种不同的可能原因。

首先,您在另一个 c++ 文件中声明了该类,这意味着当前 c++ 文件无法在您声明 main 的文件中找到它。此问题的可能解决方案是在与 main 相同的文件中声明类及其函数。

第二,你没有实际实现/声明函数 setvalues。可能的解决方案是在类内部实现 setvalues 或在类外部实现它。

第三,您在命名空间中声明了函数和类,但没有限定函数。

如果您需要示例,请告诉我。

相关文章: