gpt4 book ai didi

c++ - 如何在这里摆脱 dynamic_cast ?

转载 作者:行者123 更新时间:2023-11-30 00:39:39 26 4
gpt4 key购买 nike

我正在为我的游戏制作一个简单的图形引擎。

这是界面部分:

class Texture { ... };

class DrawContext
{
virtual void set_texture(Texture* texture) = 0;
}

这是实现部分:

class GLTexture : public Texture
{
public:
...
GLuint handle;
};

void GLDrawContext::set_texture(Texture* texture)
{
// Check if it's GLTexture, otherwise do nothing.
if (GLTexture* gl_texture = dynamic_cast<GLTexture*>(texture))
{
glBindTexture(GL_TEXTURE_2D, gl_texture->handle);
}
}

在这里使用 dynamic_cast 有意义吗?有办法避免吗?

最佳答案

你能试着扭转这个顾虑吗?

class Texture
{
public:
virtual void set_texture() = 0;
};

class GLTexture : public Texture
{
public:
virtual void set_texture();
GLuint handle;
};

void GLTexture::set_texture()
{
glBindTexture(GL_TEXTURE_2D, handle);
}

class DrawContext 
{
virtual void set_texture(Texture* texture) = 0;
};

class GLDrawContext : public DrawContext
{
virtual void set_texture(Texture* texture);
};

void GLDrawContext::set_texture(Texture* texture)
{
texture->set_texture();
}

关于c++ - 如何在这里摆脱 dynamic_cast ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8219850/

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