【问题标题】:Having problems with declaring classes with static members [duplicate]使用静态成员声明类时遇到问题[重复]
【发布时间】:2020-05-23 00:20:57
【问题描述】:

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


【解决方案1】:
CGame* CGame::s_instance = nullptr;

您的 cpp 中缺少。

【讨论】:

  • 您好,感谢您的评论,我对您的答案进行了一些编辑,所以它可以工作。 :)
猜你喜欢
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
相关资源
最近更新 更多