在派生类构造函数中使用基类构造函数



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

这是我的方法:

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 calledn";
}
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 calledn";
};
int get_val() const { return value; }  ;

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

在派生类构造函数的初始化列表中添加适当的基类构造函数'call'是完全可以接受和正常的。(实际上,对于您所展示的示例,省略了初始化列表中的构造函数将导致代码格式错误:编译器将尝试默认构造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 calledn";
} // Note: Unnecessary semicolon after function (as also after getter).
int get_val() const { return value; } // ; unnecessary
};
对于这段代码,clang-cl给出如下:

警告:字段'value'将在基数'base'之后初始化(-Wreorder-ctor)

和MSVC给出:

警告C5038:数据成员'derived::value'将被初始化基类' Base '

最新更新