我有一个像这样定义的 java 类:
class GlslProgram
{
public:
class Format {
public:
Format& vertex(const char* shader_path);
std::string m_vertex_shader;
private:
std::string load_shader(const char* shader_path);
};
void use() const;
void uniform(const GLchar* name, const GLboolean value) const;
GlslProgram() {};
GlslProgram(const Format& format, const bool separable = false);
private:
GLuint m_handle;
GLuint compile_shader(const std::string shader_string, const GLenum
};
第二个构造函数(即 GlslProgram(const Format& format, const bool separable = false);
是我唯一想使用或可用的构造函数。
我想删除默认构造函数(或将其设为私有(private)),但我不能,因为我必须在我的应用程序中将 GlslProgram
的(未初始化的)实例声明为另一个类的成员。
即
class BasicCubeExample : public Application
{
private:
virtual void set_info()
{
Application::set_info();
m_info.title = "Basic cube example";
}
// Here the format is not yet known so I can not call the correct constructor (at this time)
GlslProgram m_shader;
};
因此,通过声明 GlslProgram m_shader;
我调用了 GlslProgram
的默认构造函数(我不想这样做)并且我必须保持默认构造函数可用(我不想这样做)。
如何在不调用其默认构造函数的情况下将类的实例声明为成员变量?
最佳答案
一个解决方案(在评论和另一个答案中提到)是动态分配 BasicCubeExample
中的程序并通过智能指针保存它。
还有一个避免动态分配的替代方案,即std::optional
(或者,在 C++17 之前,boost::optional
):
class BasicCubeExample : public Application
{
private:
virtual void set_info()
{
Application::set_info();
m_info.title = "Basic cube example";
}
// Here the format is not yet known so I can not call the correct constructor (at this time)
std::optional<GlslProgram> m_shader;
};
稍后,像这样初始化它:
m_shader.emplace(format, separable);
在之后的使用中,optional
就像指针一样被取消引用,使用 *m_shader
或 m_shader->something
。
关于c++ - 如何延迟成员变量的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48109355/