c++ - 初始化列表需要其效果的初始化函数调用?

标签 c++ initialization-list

我有一个包含 const 字段成员的基 Image 类:

class Image {
protected:
    const int width;
    const int height;

public:
    virtual ~Image();
    const int getWidth() const;
    const int getHeight() const;

protected:
    Image(const int width, const int height);
};

这意味着在构造函数中,我必须像这样在初始化列表中初始化宽度和高度:

Image::Image(const int width, const int height) :
        width(width), height(height) {
}

现在我打算对其进行子类化,以便我可以通过向子类提供文件路径来加载图像(因此调用代码不必担心加载图像)。此类类似于以下内容:

class GlImage: public Image {
private:
    const GLuint textureId;
    const int textureWidth;     // power of 2 width
    const int textureHeight;    // power of 2 height
    const double textureCoordinateX;
    const double textureCoordinateY;

public:
    GlImage(const string path); // is this constructor possible?
    virtual ~GlImage();
    const double getTextureCoordinateX() const;
    const double getTextureCoordinateY() const;

private:
    // what do we use for initialization functions?
};

但是,我们可以看到这里 - 在我们获得宽度/高度之前必须加载图像 - 子类中有字段也需要在初始化列表中初始化

如何设置子类的构造函数,以便可以初始化所有这些字段?

不可能在子类中引入另一个捕获所有字段数据的对象,将其作为初始化列表中的第一个对象加载,并重新提取所有其他字段的值,因为基类需要宽度/高度(如果图像加载逻辑在派生类中则不可用)。

移除 const 修饰符并在构造函数中初始化字段是唯一的出路吗?

最佳答案

问题是您不能从派生类构造函数初始化列表中调用基类构造函数,因为您不知道维度,对吗?

为什么不在派生类上创建静态方法?

class GlImage: public Image {
    ....
    static GlImage LoadFromFile(const string& path)
    {
         // read image data and other info
         int w = ...
         int h = ...
         return GlImage(w, h, ....) 
         // of course, you would need a different ctor in derived class
         // it can even be private
    }
 }

关于c++ - 初始化列表需要其效果的初始化函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13777734/

相关文章:

c++ - pthreads SIGHUP on Simple Linux Timer

c++ - 如何初始化本身具有非平凡构造函数的对象的 STL vector ?

c++ - Valgrind 错误 : in use at exit: 72, 704 字节 C++ 初始化列表异常与 char*

C++ - 在初始化类成员之前运行一个函数

c++ - 如果我使用 BLAS/cuBLAS 以使其性能优于普通 C/CUDA,矩阵应该有多大?

c++ - gtkmm - 如何使包含小部件的框扩展以填充窗口?

c# - 这两个 List 初始化是否相同?

c++ - 没有默认构造函数的类成员

c++ - std::string 的函数指针的 typedef 不起作用

c++ - 为什么我不能使用 gcc 链接具有 C 接口(interface)的混合 C/C++ 静态库?