繁体   English   中英

如何处理可选的 class 类成员

[英]How to handle optional class members that are classes

具体来说,我的问题是我创建了一个纹理 class(编写 OpenGL 代码)。 纹理 class 处理将文件加载到 memory 等,构造函数将文件名作为其参数。 这是 class 的一些相关代码的片段。

class Texture
{
public:
    unsigned char* image;
    int width;
    int height;
    int channels;
    GLuint texture_id;

Texture(const char* image_path)
    :texture_id(NULL)

然后我有一个可以包含纹理的金字塔 class。 它可能只是一个没有纹理的彩色金字塔,因此纹理属性是可选的。

class Pyramid :
    public Shape
{
public:
    std::string get_shape_type();
    Pyramid(float height, float base_width, glm::vec4 color, glm::mat4 scale, glm::mat4 rotation, glm::mat4 translation);
    Pyramid(float height, float base_width, const char * texture_file, glm::mat4 scale, glm::mat4 rotation, glm::mat4 translation);
private:
    Texture texture;

当然,这给了我一个错误,即纹理 class 没有默认构造函数。 在这种情况下使用的一般模式是什么? 我尝试将texture(NULL)包含在 Pyramid 的构造函数初始化列表中,因为只有在文件名作为相应构造函数的一部分传入时才应设置纹理,但这并没有清除错误。

有什么建议么?

指针可以帮助你。 他们可以引用Texture或什么都不引用(通过nullptr )。

class Pyramid : public Shape
{
    Texture* m_Texture;

    Pyramid(Texture *tex = nullptr) m_Texture(tex) {};
};

笔记:

  1. Pyramid可能会或可能不会根据您的需要负责创建纹理(这意味着构造函数可能需要Texture*filename作为参数)
  2. 指针将允许您在多个Shape之间重复使用相同的Texture而无需多次加载它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM