首页 > 解决方案 > 使用静态成员声明类时遇到问题

问题描述

所以基本上我正在尝试创建一个类和一个(静态)函数来访问它,但由于某种原因,代码拒绝编译并抛出 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_

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

标签: c++class

解决方案


CGame* CGame::s_instance = nullptr;

您的 cpp 中缺少。


推荐阅读