如何处理 class 的可选 class 成员
How to handle optional class members that are classes
具体来说,我的问题是我创建了一个纹理 class(编写 OpenGL 代码)。纹理 class 处理将文件加载到内存等操作,构造函数将文件名作为其参数。这是 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) {};
};
备注:
Pyramid
可能会或可能不会根据您的需要创建纹理(这意味着构造函数可能需要 Texture*
或 filename
作为参数)
- 指针将允许您在许多
Shape
之间重复使用相同的 Texture
,而无需多次加载它们。
具体来说,我的问题是我创建了一个纹理 class(编写 OpenGL 代码)。纹理 class 处理将文件加载到内存等操作,构造函数将文件名作为其参数。这是 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) {};
};
备注:
Pyramid
可能会或可能不会根据您的需要创建纹理(这意味着构造函数可能需要Texture*
或filename
作为参数)- 指针将允许您在许多
Shape
之间重复使用相同的Texture
,而无需多次加载它们。