简体   繁体   English

用相同的参数调用基类的C ++构造函数

[英]Call C++ constructor of base class with same arguments

I've ve something like this: 我有这样的事情:

class A {
public:
  A(int a1,int a2,int a3) {
  }
}
class B: public A {
public:
  B(int a1,int a2,int a3) : A(a1,a2,a3) { 
     .. Do Some More Init for B ...
  }
}

Is it possible to write the constructor in aa shorter form? 是否可以用较短的形式编写构造函数? The Constructor of the base class should be called with the same arguments. 基类的构造函数应使用相同的参数调用。 But I don't want to list all of the arguments explicit. 但是我不想明确列出所有参数。 And I need to do some special initialization stuff for class B. 我需要为B类做一些特殊的初始化工作。

I think something like this: 我认为是这样的:

class B: public A {
public:
  B(int a1,int a2,int a3) : A(...AUTOARG...) { 
    .. Do Some More Init for B ...
  }
}

Is this possible in C++/11? 在C ++ / 11中可能吗?

If there is no code happening inside B 's constructor and you simply want to allow its construction in the same ways A is constructible, you can inherit A 's constructors: 如果B的构造函数内没有代码发生,并且您只想以A可以构造的相同方式允许其构造,则可以继承 A的构造函数:

class B: public A {
public:
  using A::A;
};

This will give B all the same constructors as A has. 这将为B提供与A相同的所有构造函数。

If, as the edited question says, B 's constructor is not empty, you can still get "do all A does plus some more" in a generic (but not as nice) way using a "catch-all" constructor with perfect forwarding: 如所编辑的问题所述,如果B的构造函数不为空,则仍可以使用具有完美转发功能的“包罗万象”构造函数以通用(但效果不佳)的方式获得“全部完成A功能,再加上更多的功能” :

class B: public A {
public:
  template <class... Arg>
  B(Arg&&... arg) : A(std::forward<Arg>(arg)...) { 
     //.. Do Some More Init for B ...
  }
}

Note that this changes B 's behaviour slightly with respect to type traits. 请注意,就类型特征而言,这会稍微改变B的行为。 It now seems constructible from anything, but using incorrect arguments will fail to compile. 现在看来可以用任何东西构造,但是使用不正确的参数将无法编译。 If you also need the class to play nice with constructibility detection traits etc., you can conditionally disable the incorrect instantiations using SFINAE . 如果您还需要该类在可构造性检测特性等方面发挥出色的作用 ,则可以使用SFINAE有条件地禁用不正确的实例化。

Better still, inherit the constructor. 更好的是, 继承构造函数。 This is a new feature from C++11: 这是C ++ 11的新功能:

class B: public A {
public:
  using A::A;
};

Unfortunately though, if you want the B constructor to do additional things, then you'll need to write it out longhand as you currently do. 但是,不幸的是,如果您希望B构造函数执行其他操作,那么您将需要像现在这样将其写出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM