我面临的问题与“循环包含”或“未完成的课程”有关
我有2节课:
ControllerManager,此类声明为Singleton,此类具有AuxController对象。
AuxController,此类具有需要获取ControllerManager实例的函数
问题是:编译源代码时,它失败,并显示错误“不完整类型”或“无效类型”
有什么办法可以解决这个问题?
还是有其他方法可以重新设计代码结构?
源代码
ControllerManager.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
ControllerManager.cpp
#include "controllermanager.h"
/* 5. initialize static variable */
ControllerManager *ControllerManager::inst = 0;
ControllerManager::ControllerManager()
{
m_code = 15;
}
ControllerManager::~ControllerManager()
{
delete inst;
}
AuxController.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
AuxController.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);
}
main.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文件中所有必需的头文件。