我最近又开始用C++编程,出于教育的目的,我正致力于创建一个扑克游戏。奇怪的是,我一直收到以下错误:
1>LearningLanguage01.obj : error LNK2019: unresolved external symbol "public: __thiscall PokerGame::Poker::Poker(void)" (??0Poker@PokerGame@@QAE@XZ) referenced in function "void __cdecl `dynamic initializer for 'pokerGame''(void)" (??__EpokerGame@@YAXXZ)
1>LearningLanguage01.obj : error LNK2019: unresolved external symbol "public: __thiscall PokerGame::Poker::~Poker(void)" (??1Poker@PokerGame@@QAE@XZ) referenced in function "void __cdecl `dynamic atexit destructor for 'pokerGame''(void)" (??__FpokerGame@@YAXXZ)
1>LearningLanguage01.obj : error LNK2019: unresolved external symbol "public: void __thiscall PokerGame::Poker::begin(void)" (?begin@Poker@PokerGame@@QAEXXZ) referenced in function _wmain
1>C:\Visual Studio 2012\Projects\LearningLanguage01\Debug\LearningLanguage01.exe : fatal error LNK1120: 3 unresolved externals我在这个问题上做了一些研究,大部分都是因为头部和.cpp中的构造函数和析构函数定义不匹配。我看不出头部和.cpp有任何问题。
下面是poker.h的代码:
#pragma once
#include "Deck.h"
using namespace CardDeck;
namespace PokerGame
{
const int MAX_HAND_SIZE = 5;
struct HAND
{
public:
CARD cards[MAX_HAND_SIZE];
};
class Poker
{
public:
Poker(void);
~Poker(void);
HAND drawHand(int gameMode);
void begin();
};
}以及.cpp中的代码:
#include "stdafx.h"
#include "Poker.h"
using namespace PokerGame;
const int TEXAS_HOLDEM = 0;
const int FIVE_CARD = 1;
class Poker
{
private:
Deck deck;
Poker::Poker()
{
deck = Deck();
}
Poker::~Poker()
{
}
void Poker::begin()
{
deck.shuffle();
}
//Draws a hand of cards and returns it to the player
HAND Poker::drawHand(int gameMode)
{
HAND hand;
if(gameMode == TEXAS_HOLDEM)
{
for(int i = 0; i < sizeof(hand.cards); i++)
{
hand.cards[i] = deck.drawCard();
}
}
return hand;
}
};发布于 2013-01-06 20:46:59
由于下面的评论,我重写了以前的内容。
链接器抱怨的问题是,您已经在Poker中声明了成员函数,但没有定义它们。这怎么回事?对于初学者,您将创建一个新类并在其中定义单独的成员函数。
头文件Poker类位于PokerGame名称空间中,cpp文件Poker类位于全局名称空间中。要解决此问题,请将它们放在相同的名称空间中:
//cpp file
namespace PokerGame {
class Poker {
...
};
}既然它们在同一个名称空间中,您就有了另一个问题。您在类体中定义了成员函数,但不是第一个。定义不能以相同的方式放在命名的类的主体中。删除cpp文件中的整个类:
//cpp file
namespace PokerGame {
Poker::Poker() {
deck = Deck(); //consider a member initializer instead
}
//other definitions
}最后一件事:您将类的私有部分放在了错误的位置。它就在我们刚刚删除的cpp file类中。它属于类的其他部分:
//header file
namespace PokerGame {
class Poker {
public:
//public stuff
private:
Deck deck; //moved from cpp file
};
}发布于 2013-01-31 05:51:20
另一种解决方案可能是:检查cmake文件,并确保它(例如在ADD_EXECUTABLE中)包含您列出的.cpp文件。
https://stackoverflow.com/questions/13318965
复制相似问题