gpt4 book ai didi

c++ - 无法从其他类获取单例类的实例

转载 作者:太空宇宙 更新时间:2023-11-04 16:03:39 25 4
gpt4 key购买 nike

我面临的问题在某种程度上与“循环包含”或“未完成的类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com