我刚才问过how to use virtual classes in 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
有Graphics.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
Graphics.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
当在graphics.cpp中显然有一个构造函数时。有人可以解释编译器在这里抱怨什么吗?
编辑:
不确定它是否意味着什么,但当鼠标悬停在MSVC中的小红色波浪上时,它说,“不允许抽象类类型Graphics :: Model的对象”。 ...但它没有任何纯粹的虚拟成员,所以它不抽象吗?
编辑:
根据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'
答案 0 :(得分:1)
您在定义之前使用Model类。在单独的CPP中定义函数CreateModel,它可能有效。