我面临的问题在某种程度上与“循环包含”或“未完成的类(class)”有关
我有 2 个类:
ControllerManager,这个类声明为Singleton,这个类有一个对象AuxController。
AuxController,这个类有个函数需要获取ControllerManager的实例
问题是:编译源码时,编译失败,报错“类型不完整”或“类型无效”
有什么办法可以解决这个问题吗? 或者有没有其他方法可以重新设计代码结构?
源代码 Controller 管理器.h
#ifndef CONTROLLERMANAGER_H
#define CONTROLLERMANAGER_H
#include "auxcontroller.h"
class ControllerManager
{
/* This class is defined as Singleton class */
private:
/* 1. define a private static instance */
static ControllerManager *inst;
public:
/* 2. define a public static accessor */
static ControllerManager *getInstance(){
/* 3. do lazy initialization */
if(!inst){
inst = new ControllerManager();
}
return inst;
}
protected:
/* 4. Define all accessors to be protected */
ControllerManager();
~ControllerManager();
/* property */
private:
int m_code;
public:
int getCode()
{
return m_code;
}
void setCode(int _code)
{
m_code = _code;
}
/* below code causes fail of compilation */
public:
AuxController m_auxcontroller;
};
#endif // CONTROLLERMANAGER_H
Controller 管理器.cpp
#include "controllermanager.h"
/* 5. initialize static variable */
ControllerManager *ControllerManager::inst = 0;
ControllerManager::ControllerManager()
{
m_code = 15;
}
ControllerManager::~ControllerManager()
{
delete inst;
}
辅助 Controller .h
#ifndef AUXCONTROLLER_H
#define AUXCONTROLLER_H
/* if do NOT include controllermanager.h with below line,
* and declare ControllerManager class as a forward declaration:
*
* class ControllerManager;
*
* compiler will stop due to "incomplete type"
*/
#include "controllermanager.h"
class AuxController
{
public:
AuxController();
void setControllerCode(int code);
};
#endif // AUXCONTROLLER_H
辅助 Controller .cpp
#include "auxcontroller.h"
AuxController::AuxController()
{
}
void AuxController::setControllerCode(int code)
{
/* if do NOT include controllermanager.h ,
* and declare ControllerManager class as a forward declaration in the header file:
*
* class ControllerManager;
*
* compiler will stop due to "incomplete type" at this line
*
*/
ControllerManager::getInstance()->setCode(code);
}
主要.cpp
#include "controllermanager.h"
int main(int argc, char *argv[])
{
ControllerManager *ctlMng = ControllerManager::getInstance();
ctlMng->setCode(10);
return 0;
}
最佳答案
不要在 auxcontroller.h 中包含“controllermanager.h”,但要在 auxcontroller.cpp 中包含它。
一般情况下,如果可以避免的话,您不应该将头文件包含在其他头文件中。请改用前向声明。但是一定要包含 cpp 文件中所有必需的头文件。
关于c++ - 无法从其他类获取单例类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39246224/