多年來,我一直在開發C#和Java(在許多其他語言之間),而現在我只是在C++中弄溼了自己的腳。我把自己埋在了繼承和類的資源之中,但我似乎無法弄清楚如何擺脫這個令人討厭的錯誤。重載默認構造函數導致錯誤
我的代碼:
Entity.h
:
#ifndef ENTITY_H
#define ENTITY_H
#include <iostream>
class Entity
{
public:
std::string m_name;
void update(float delta);
Entity();
private:
virtual void step(float delta);
};
#endif
Entity.cpp
:
#include "Entity.h"
Entity::Entity()
{
m_name = "Generic Entity";
}
void Entity::update(float delta)
{
step(delta);
}
void Entity::step(float delta) {}
Player.h
:
#ifndef PLAYER_H
#define PLAYER_H
#include "Entity.h"
class Player : public Entity
{
public:
Player();
private:
virtual void step(float delta);
virtual void draw() const;
};
#endif
Player.cpp
:
#include "Player.h"
Player::Player()
{
m_name = "Player";
}
void Player::step(float delta) {}
void Player::draw() const {}
Main.cpp
:
int main()
{
return 0;
}
正如你所看到的,我不這樣做與類的任何信息,但我發現這些錯誤:
Error 3 error LNK1120: 1 unresolved externals C:\[...]\Debug\ConsoleApplication1.exe ConsoleApplication11
Error 2 error LNK2019: unresolved external symbol "public: __thiscall Entity::Entity(void)" ([email protected]@[email protected]) referenced in function "public: __thiscall Player::Player(void)" ([email protected]@[email protected]) C:\[...]\ConsoleApplication1\Player.obj ConsoleApplication1
更新:代碼奇蹟般地工作,當我註釋掉Player.cpp
中的以下代碼時:
/*Player::Player()
{
m_name = "Player";
}*/
如何編譯它?並且私有虛擬方法沒有意義 – 2014-11-02 03:30:28
看起來您並未鏈接「Entity.cpp」的目標代碼,很可能是因爲您沒有編譯該文件。還要注意,要使用'std :: string',你應該包含'',而不是''。儘管代碼可能與某些編譯器一起編譯,但它可能無法與其他編譯器一起編譯。 –
2014-11-02 03:30:34
@BryanChen Microsoft Visual Studio Express 2013 for Windows Desktop – Entity 2014-11-02 03:30:58