在派生 [=s10=] 构造函数中使用基 class 构造函数

Using base class constructor in derived class contructor

假设我想使用基础 class 构造函数来创建派生的 class 对象。

这是我的方法:

class base
{
    int x, y, z;
public:
    base(int x, int y, int z)
        :
        x(x),
        y(y),
        z(z)
    {
        std::cout << "base class constructor called\n";
    }
    int get_x() const { return x; }
    int get_y() const { return y; }
    int get_z() const { return z; }
};

class derived : public base
{
    int value;
public:
    derived(int x, int y, int z, int value)
        :
        base(x, y, z),
        value(value)
    {
        std::cout << "derived class constructor called\n";
    };
    int get_val() const { return value; }  ;
    
};

我的问题:这是解决该问题的正确方法吗?或者,关于如何在派生 class 构造函数中使用基 class 构造函数,是否有更好的方法?

在派生 class 构造函数的初始化列表中添加适当的基础 class 构造函数 'call' 是完全可以接受的,也是正常的。 (事实上,对于您展示的示例,从初始化列表中省略 构造函数将导致代码格式错误:编译器随后将尝试默认构造 base 对象,并且由于您指定了显式的参数获取构造函数,因此 base class 的默认构造函数被删除。)

然而,需要注意的一点是,基础 class 构造函数将 首先执行 ,即使您重新排列该初始化列表中的规范顺序也是如此。

采用下面稍微修改的代码:

class derived : public base {
    int value;
public:
    derived(int x_, int y_, int z_, int value_) // IMHO, using argument names same as members not good
        :
        value(value_),      // Rearrange list to have this appear first ...
        base(x_, y_, z_)    // ...but this is STILL called before the above
    {
        std::cout << "derived class constructor called\n";
    } // Note: Unnecessary semicolon after function (as also after getter).
    int get_val() const { return value; } // ; unnecessary
};

对于这段代码,clang-cl 给出了这个:

warning : field 'value' will be initialized after base 'base' [-Wreorder-ctor]

而 MSVC 给出:

warning C5038: data member 'derived::value' will be initialized after base class 'base'