我正在尝试实现我在书中找到的单例设计模式,我知道我可能不需要在这里使用单例但是除了我创建了一个GamePropertiesManager并且我得到了以下编译(或者更确切地说,链接器?)错误:Main.cpp|| undefined reference to GamePropertiesManager::GetInstance
我正试图在我的主函数中使用我的单例,如此...
#include "GamePropertiesManager.hpp"
..
int main()
{
GamePropertiesManager::Create();
GamePropertiesManager::GetInstance()->test();
...
}
我的GamePropertiesManager在头文件中定义如下:
class GamePropertiesManager
{
public:
static GamePropertiesManager* GetInstance();
static void Create();
static void Destroy();
void test();
protected:
GamePropertiesManager();
static GamePropertiesManager* _instance;
enum GameMode{ PLAYERVSPLAYER, PLAYERVSCOM };
GameMode _gameMode;
std::string _player1Name, _player2Name;
int _player1Score, _player2Score;
std::string _matchSurvivor;
int _gameSpeed;
};
并在单独的cpp文件中声明:
#include "GamePropertiesManager.hpp"
//testic
#include <iostream>
GamePropertiesManager* GamePropertiesManager::_instance = NULL;
void GamePropertiesManager::Create()
{
if (!_instance) //instance not yet created
_instance = new GamePropertiesManager();
}
void GamePropertiesManager::Destroy()
{
delete _instance;
_instance = 0;
}
GamePropertiesManager::GamePropertiesManager() :
_gameMode(PLAYERVSCOM), _player1Name("Player 1"), _player2Name("Player 2"),
_player1Score(0), _player2Score(0), _matchSurvivor("NONE"), _gameSpeed(1)
{
}
void GamePropertiesManager::test()
{
std::cout << "test success!" << std::endl;
}
如果有人可以查看它,请解释我做错了什么,我非常感激!
答案 0 :(得分:3)
您已声明了一个函数static GamePropertiesManager* GetInstance();
但未对其进行定义。实际上,您的GamePropertiesManager::Create()
正在完成大部分工作。如果我是你,我会摆脱它并替换为:
GamePropertiesManager* GamePropertiesManager::GetInstance()
{
if (!_instance) //instance not yet created
_instance = new GamePropertiesManager();
return _instance;
}
答案 1 :(得分:1)
正如它在锡上所说的那样。您已声明GetInstance
函数并尝试调用它,但您实际上尚未定义该函数的实现。
答案 2 :(得分:1)
我看到了GetInstance()的声明,但没有定义。也许你只是忘了写它?
答案 3 :(得分:1)
您忘了定义GetInstance()!
答案 4 :(得分:1)
您必须实现静态函数GetInstance()。
我会摆脱_instance并按照这样做:
GamePropertiesManager* GamePropertiesManager::GetInstance()
{
static GamePropertiesManager manager;
return &manager;
}