开发者

Unresolved externals error

开发者 https://www.devze.com 2023-04-03 21:03 出处:网络
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.

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 explicit开发者_运维百科ly 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().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号