簡體   English   中英

無法解決的外部錯誤

[英]Unresolved externals error

我知道有很多這樣的問題,但是我不確定我到底在做什么錯。 我有兩個類,Player和HumanPlayer。 HumanPlayer應該從Player類繼承。 當我嘗試在HumanPlayer.cpp文件中執行構造函數並進行編譯時,出現以下錯誤:

錯誤2錯誤LNK1120:1個未解決的外部

錯誤1錯誤LNK2001:無法解析的外部符號“ public:__thiscall Player :: Player(void)”(?? 0Player @@ QAE @ XZ)

我讀到您需要在派生類的構造函數中顯式調用基類,因此我相信我已經做到了,因為編譯器不會對此引發錯誤。 如果有人能指出我正確的方向,那就太好了。 我也在使用MS Visual Studio 2010。

這是有問題的文件:

//Player.h
#pragma once
#include <string>
using namespace std; 

class Player{

public: 
    Player(); 

    Player(const string &); 

    void setName(string); 
    string getName(); 
    void sowSeeds(); 

    void play(); 

private: 
    string name; 
}; 

//Player.cpp

#include <iostream>
#include "Player.h"

using namespace std;

//constructor
Player::Player(const string &enteredName){
    name = enteredName; 
}

//HumanPlayer.h

#pragma once

#include <string>
#include "Player.h"
using namespace std; 

class HumanPlayer : public Player{

public: 
    HumanPlayer(); 

    HumanPlayer(const string &); 

private: 

}; 

//HumanPlayer.cpp

#include <iostream>
#include "Player.h"
#include "HumanPlayer.h"

using namespace std;

//constructor
HumanPlayer::HumanPlayer() : Player(){

}

HumanPlayer::HumanPlayer(const string &enteredName) : Player(enteredName){

}

您沒有實現不帶任何參數的構造函數Player::Player() 而且由於HumanPlayer::HumanPlayer()調用了您從未實現的Player::Player()構造函數,因此您遇到了問題。

在Player.cpp中,您需要為默認構造函數添加定義。

Player::Player()
: name( "anonymous-player" )
{}

但是也許您不希望玩家能夠匿名,在這種情況下,您應該刪除該行

Player();

來自Player.h。 由於您已經聲明了一個帶有字符串參數的構造函數,因此編譯器不會自動為Player類生成默認的構造函數,並且沒有人可以在不提供播放器名稱的情況下實例化它。

您不需要手動調用基本構造函數,否則,編譯器將調用默認構造函數(除非使用虛擬繼承)。 您只需要實現該默認構造函數Player :: Player()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM