创建一种c++接口



我正在写一个小的2d渲染框架与管理器的输入和资源,如纹理和网格(2d几何模型,如四边形),他们都包含在一个类"引擎",与他们和directX类交互。每个类都有一些公共方法,比如init或update。它们由引擎类调用来渲染资源,创建资源,但其中很多不应该由用户调用:

//in pseudo c++
//the textures manager class
class TManager
{
  private:
     vector textures;
     ....
  public:
     init();
     update();
     renderTexture();
     //called by the "engine class"
     loadtexture();
     gettexture();
     //called by the user
}

class Engine
{
private:
   Tmanager texManager;
public:
     Init() 
     { 
       //initialize all the managers
     }
     Render(){...}
     Update(){...}
     Tmanager* GetTManager(){return &texManager;} //to get a pointer to the manager 
                                                  //if i want to create or get textures
}

通过这种方式,用户调用Engine::GetTmanager将有权访问Tmanager的所有公共方法,包括init update和rendertexture,这些方法必须仅由Engine在其init, render和update函数中调用。那么,以以下方式实现用户界面是个好主意吗?

//in pseudo c++
//the textures manager class
class TManager
{
  private:
     vector textures;
     ....
  public:
     init();
     update();
     renderTexture();
     //called by the "engine class"
     friend class Tmanager_UserInterface;
     operator Tmanager_UserInterface*(){return reinterpret_cast<Tmanager_UserInterface*>(this)}
}
class Tmanager_UserInterface : private Tmanager
{
  //delete constructor
  //in this class there will be only methods like:
   loadtexture();
   gettexture();
}
class Engine
{
private:
   Tmanager texManager;
public:
     Init() 
     Render()
     Update()
     Tmanager_UserInterface* GetTManager(){return texManager;}
}
//in main function
   //i need to load a texture
   //i always have access to Engine class 
engine->GetTmanger()->LoadTexture(...) //i can just access load and get texture;

通过这种方式,i可以为每个对象实现多个接口,只保持i(和用户)需要的函数可见。

有更好的方法做同样的事吗??或者它只是无用的(我没有隐藏"框架私有函数",用户将学会不调用它们)?

在我使用这个方法之前:

class manager
{
 public:
   //engine functions
   userfunction();
}
class engine
{ 
 private:
 manager m;
  public:
   init(){//call manager init function}
   manageruserfunciton()
   {
    //call manager::userfunction()
   }
}

这样我就不能访问管理器类了但这是一种不好的方式,因为如果我添加我需要在引擎类中添加一个新方法,这需要花费很多时间。

对不起,我的英语不好。

您可以使用您的方法,但是最好从公共接口派生私有接口:

class TexManagerPublic
{
public:
    virtual void load() = 0;
    virtual void save() = 0;
};
class TexManagerPrivate : public TexManagerPublic
{
public:
    void load();
    void save();
    void init();
    void update();
};
class Engine
{
    TexManagerPrivate theTexManager;
public:
    Engine() { theTexManager.init(); }
    TexManagerPublic* texManager() { return &theTexManager; }
};

或者你可以让一个'Engine'成为TextureManager的朋友,像这样:

class TexManager
{
private:
    void init();
    void update();
    friend class Engine;
};
class Engine
{
    TexManager texManager;
    void init()
    {
        texManager.init();
    }
};

相关内容

最新更新