【问题标题】:Using base class constructor in derived class contructor [closed]在派生类构造函数中使用基类构造函数[关闭]
【发布时间】:2021-11-11 13:38:22
【问题描述】:

假设我想利用基类构造函数来创建派生类对象。

这是我的做法:

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; }  ;
    
};

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

【问题讨论】:

  • 显示的代码看起来不错。
  • derived(base b, int value) 这样的构造函数可能有意义。
  • 是的,这是创建派生对象的标准方法。

标签: c++ c++11 inheritance c++14


【解决方案1】:

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

然而,需要注意的是,基类构造函数将首先执行,即使您在初始化列表中重新排列规范顺序。

取下面稍作修改的代码:

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 给出:

警告:字段 'value' 将在 base 'base' 之后初始化 [-Wreorder-ctor]

MSVC 给出:

警告 C5038:数据成员 'derived::value' 将在之后初始化 基类'base'

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 2018-07-21
    • 2015-08-18
    • 2018-07-16
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多