简体   繁体   English

稍微派生一个类而不会失去对其构造函数的访问权限

[英]Slightly derive a class without loosing access to its constructors

Suppose I have a large class with a lot of functionality and a relatively large interface. 假设我有一个具有很多功能和相对大的接口的大类。 Particularly, there are many constructors for convenient instantiation. 特别是,有许多构造函数可以方便地实例化。 From this class, several classes could be derived with some slightly extended interface and/or customized virtual functions. 从这个类中,可以通过一些稍微扩展的接口和/或定制的虚函数来派生几个类。

The problem: I will have to copy all the constructors into the derived classes which would mean a lot of code duplication. 问题:我必须将所有构造函数复制到派生类中,这意味着需要大量的代码重复。 Even worse: The constructors slightly depend on the derived class, which I would solve by a virtual call, but this does not work in a constructor. 更糟糕的是:构造函数稍微依赖于派生类,我将通过虚拟调用来解决,但这在构造函数中不起作用。

What's a good approach to tackle this problem? 解决这个问题的好方法是什么?

EDIT: I know that I can delegate constructors Derived(arguments) : Base(arguments) {} but I'd still need to copy parts of the constructor which I try to avoid. 编辑:我知道我可以委托构造函数Derived(arguments) : Base(arguments) {}但是我仍然需要复制我试图避免的构造函数的部分。

Use using declarations to make the constructors of the base class aviable on the derived one: 使用using声明使基类的构造函数上得到的一个aviable:

class Base
{
public:
    Base( int , int , int );
};

class Derived : public Base
{
public:
    using Base::Base; //Automatically adds all the base constructors
};

EDIT: Here is a running example. 编辑: 是一个运行的例子。

I do not know exactly if it works for your problem, but you might think about making some kind of 'initialization' object where you handle the properties of the object you want to create. 我不确切知道它是否适用于您的问题,但您可能会考虑制作某种“初始化”对象,您可以在其中处理要创建的对象的属性。 This will have a lot of constructors. 这将有很多构造函数。

Then you pass this object to the 'real' class where the properties are used to create the actual object. 然后将此对象传递给'real'类,其中属性用于创建实际对象。

If C++ 11 extensions can be used, then the other answer that recommends using is a perfect answer. 如果可以使用C ++ 11扩展,那么建议using的另一个答案是一个完美的答案。

If not, then the only way is: 如果没有,那么唯一的方法是:

class x:  public y
{
    // modified constructors:

    x (int a) : y (1, 2, a + 3) { your code if any; }
    x (int a, int b) : y (b, a) { your code if any; }

    // delegated constructors: alas, repeated for all constructors of y

    x (int c, float d) : y (c, d) { /* no code*/ }
    x (float e, int f) : y (e, f) { /* no code*/ }
}

The latter part is not really code duplication because you only duplicate interface but no code. 后一部分并不是真正的代码重复,因为你只复制接口但没有代码。

Do the initializations applicable in respective classes. 初始化适用于各自的类。 For example, say A is superclass and B is a subclass, so you may use, 例如,假设A是超类而B是子类,所以你可以使用,

B::B(...arguments...): A(...arguments that you would like to pass to superclass constructor)
{
}

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

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