简体   繁体   中英

Unresolved externals error

I know there's a lot of these sorts of questions but I'm not sure what I'm doing wrong exactly. I have two classes, Player and HumanPlayer. HumanPlayer is supposed to inherit from the Player class. When I'm trying to do the constructors in the HumanPlayer.cpp file and compile, I get the following errors:

Error 2 error LNK1120: 1 unresolved externals

Error 1 error LNK2001: unresolved external symbol "public: __thiscall Player::Player(void)" (??0Player@@QAE@XZ)

I read that you need to explicitly call the base class within the constructor of the derived class, so I believe I've done that since the compiler isn't throwing an error about it. If anyone could point me in the right direction, that would be great. I'm also using MS Visual Studio 2010.

Here are the files in question:

//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){

}

You did not implement the constructor Player::Player() that takes no arguments. And since HumanPlayer::HumanPlayer() calls the Player::Player() constructor that you never implemented, you have a problem.

In Player.cpp, you need to add the definition for the default constructor.

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

But maybe you do not want a player to be able to be anonymous, in which case you should delete the line

Player();

from Player.h. Since you've declared a constructor that takes a string argument the compiler will not auto-generate a default constructor for the Player class, and no one will be able to instantiate it without supplying a player name.

You don't need to call the base constructor manually, if you don't the compiler will call the default one (unless using virtual inheritance). You just need to implement that default constructor, Player::Player().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM