下面的代码无法实例化Display_OpenGL类,因为它不考虑Surface_OpenGL中的Surface实现来映射Display:Surface类。
取消注释这一行可以解决问题,但这并不优雅。 // void Draw(){Surface_OpenGL :: Draw(); }
对于我想做的事情,是否有更好的解决方案? Draw已在Surface_OpenGL中定义,但似乎需要为Display显式定义,还有任何不错的解决方案吗?
谢谢。
class Surface
{
public:
virtual void Draw() = 0;
};
class Display : public Surface
{
};
class Surface_OpenGL : public Surface
{
public:
void Draw(){}
};
class Display_OpenGL : public Display, public Surface_OpenGL
{
public:
//void Draw() { Surface_OpenGL::Draw(); }
};
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
//Error cannot instantiate abstract class
Display *display = new Display_OpenGL();
display->Draw();
delete display;
return 0;
}
答案 0 :(得分:2)
这就像他经典的钻石继承案例。尝试:
class Surface
{
public:
virtual void Draw() = 0;
};
class Display : virtual public Surface
{
};
class Surface_OpenGL : virtual public Surface
{
public:
void Draw(){}
};
class Display_OpenGL : public Display, public Surface_OpenGL
{
public:
//void Draw() { Surface_OpenGL::Draw(); }
};
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
//Error cannot instantiate abstract class
Display *display = new Display_OpenGL();
display->Draw();
delete display;
return 0;
}