使用静态成员声明类时遇到问题

Having problems with declaring classes with static members

本文关键字:遇到 问题 声明 静态成员      更新时间:2023-10-16

所以基本上我正在尝试创建一个类和一个(静态(函数来访问它,但由于某种原因,代码拒绝编译并抛出 2 个"未解决的外部符号"错误。

// game.cpp
#include "game.h"
CGame::CGame()
{
// ...
}
CGame* CGame::getInstance()
{
if (s_instance == nullptr)
s_instance = new CGame();
return s_instance;
}
void CGame::run()
{
// ...
}

// main.cpp
#include "game.h"
int main()
{
CGame::getInstance()->run();
}

#ifndef _GAME_
#define _GAME_
class CGame
{
private:
static CGame* s_instance;
public:
static CGame* getInstance();
void run(); // For testing purposes
CGame();
};
#endif _GAME_

这里有什么问题,我怎么可能创建一个我 [可以] 使用的类而不声明它?

CGame* CGame::s_instance = nullptr;

在您的每次转化费用中缺失。