【发布时间】:2014-02-11 03:21:42
【问题描述】:
我有两个具有单独标题的类:class Renderer 和 class Texture。 Texture 实例旨在管理驻留在Renderer 的内存池中的一些数据,因此Texture 实例不能独立于Renderer 实例而存在。要获得Texture 实例的句柄,只需使用正确的文件名调用Renderer::loadTexture,然后Renderer 在其数据库中搜索具有匹配文件名的Texture 对象,如果找不到匹配项,则实例化一个新纹理。
//renderer.h
#include "texture.h"
class renderer
{
public:
Texture* loadTexture(std::string fileName);
private:
std::map<std::string, Texture*> textureDb;
};
//texture.h
class Texture
{
public:
Texture(std::string imageFileName);
};
我突然想到,将class Texture 的构造函数设为私有,并将Texture * Renderer::loadTexture(std::string filename) 声明为class Renderer 的朋友是合乎逻辑的:
//renderer.h
#include "texture.h"
class renderer
{
public:
Texture* loadTexture(std::string fileName);
private:
std::map<std::string, Texture*> textureDb;
};
//texture.h
class texture;
#include "renderer.h"
class Texture
{
private:
Texture(std::string imageFileName);
Texture(const Texture &);
friend Texture* loadTexture(std::string);
};
但是,只有在包含 renderer.h 之前始终包含 texture.h 时才会编译,因为 class Texture 要求 class Renderer 已经定义。防止这种情况的最佳方法是什么? 两个文件中都有包含保护,但为简洁起见,此处省略。
【问题讨论】:
标签: c++ friend circular-dependency