实例化派生自接口的类,该接口位于派生自接口的另一个类中...只需阅读即可找出答案

Instantiating a class that derives from an interface that's inside another class that derives from an interface... just read to find out

本文关键字:接口 派生 答案 于派生 另一个 实例化      更新时间:2023-10-16

我刚才问过如何在 c++ 中使用虚拟类,令我沮丧的是,我得知你不能。但是一个用户(即"Emilio Garavaglia"感谢一堆),发布了一种获取类似于虚拟类的方法,只是有一些额外的代码。但是,我在编译时遇到了一些麻烦。代码如下:

global_defs.h

#define Interface class
#define abstract_class class
#define implements : public 

I_Graphics.h

#ifndef I_GRAPHICS_H
#define I_GRAPHICS_H
#include <string>
#include "global_defs.h"
Interface I_Graphics
{
public:
    virtual ~I_Graphics() {};
    virtual void Initialize() = 0;
    virtual void Frame() = 0;
    virtual void Shutdown() = 0;
    class I_Model;
    virtual I_Model * CreateModel() = 0;
};
Interface I_Graphics::I_Model
{
public:
    virtual ~I_Model() {}
    virtual void Initialize(std::string const & filename, std::string const & textureFilename) = 0;
    virtual void * GetVertexBuffer() = 0;
    virtual void * GetIndexBuffer() = 0;
};

#endif

图形.h

#ifndef GRAPHICS_H
#define GRAPHICS_H
#include "global_defs.h"
#include <map>
#include <string>
#include <memory>
#include "I_Graphics.h"
class Graphics implements I_Graphics
{
public:
    Graphics();
    ~Graphics();
    void Initialize();
    void Frame();
    void Shutdown();
    class Model;
    I_Model * CreateModel() {return new Model;}   // <--- compile error here
private:
    std::map <std::string, I_Model *> m_ModelList;
};
class Graphics::Model implements I_Graphics::I_Model
{
public:
    Model();
    ~Model();
    void Initialize(std::string filename, std::string textureFilename);
    void * GetVertexBuffer();
    void * GetIndexBuffer();
};
#endif

图形.cpp这里什么都没有,还没有真正开始处理困难的部分,只是试图让模型实例化工作。

#include "Graphics.h"
Graphics::Graphics()
{
}
Graphics::~Graphics()
{
}
void Graphics::Initialize()
{
}
void Graphics::Frame()
{
}
void Graphics::Shutdown()
{
}
Graphics::Model::Model()
{
}
Graphics::Model::~Model()
{
}
void Graphics::Model::Initialize(std::string filename, std::string textureFilename)
{

}
void * Graphics::Model::GetVertexBuffer()
{
    return NULL;
}
void * Graphics::Model::GetIndexBuffer()
{
    return NULL;
}

所以,正如小评论所说,我在那里得到一个错误,说:

error C2512: 'Graphics::Model' : no appropriate default constructor available

当图形中显然有一个构造函数时.cpp.有人可以解释一下编译器在这里抱怨什么吗?

编辑:
不确定它是否意味着什么,但是当将鼠标悬停在 MSVC 中的红色小波浪线上时,它说:"抽象类类型的对象 Graphics::模型是不允许的"。...但它没有任何纯虚拟成员,所以它不是抽象的吧?

编辑:
在Castilho的建议下,我像以前一样在graphics.h中声明CreateModel,但随后在graphics.cpp中定义了它,它产生了一个更具体的错误,但我仍然不明白为什么。

error C2259: 'Graphics::Model' : cannot instantiate abstract class
1> due to following members:
1> 'void I_Graphics::I_Model::Initialize(const std::string &,const std::string &)' : is abstract
1> i_graphics.h(28) : see declaration of 'I_Graphics::I_Model::Initialize'

在定义模型类之前使用它。在单独的 CPP 中定义函数 CreateModel,它可能会起作用。