gpt4 book ai didi

c++ - 抽象类不直接映射,有什么优雅的解决方案吗?

转载 作者:行者123 更新时间:2023-11-28 02:33:50 25 4
gpt4 key购买 nike

下面的代码无法实例化 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;
}

最佳答案

这就像他经典的菱形继承(钻石问题)案。尝试:

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;
}

关于c++ - 抽象类不直接映射,有什么优雅的解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com