通过抽象类将参数传递给祖父母类的构造函数

Passing arguments through an abstract class to the grandparent class’s constructor

本文关键字:祖父母 构造函数 参数传递 抽象类      更新时间:2023-10-16

我有一个由库提供的类Grandparent。我想为Grandparent的子类定义一个接口,所以我创建了一个名为Parent:的抽象子类

class Grandparent {
    public:
        Grandparent(const char*, const char*);
};
class Parent : public Grandparent {
    public:
        virtual int DoSomething() = 0;
};

Grandparent的构造函数接受两个参数。我希望我的子类Child也有一个带有两个参数的构造函数,并将它们传递给Grandparent的构造函数…类似

class Child : public Parent {
    public:
        Child(const char *string1, const char *string2)
        : Grandparent(string1, string2)
        {}
        virtual int DoSomething() { return 5; }
};

当然,Child的构造函数不能调用其祖父母类的构造函数,只能调用其父类的构造函数。但是由于Parent不能有构造函数,我如何将这些值传递给祖父母的构造函数?

Parent当然可以有一个构造函数。如果要用任何参数调用Grandparent构造函数,它必须这样做。

没有什么可以禁止抽象类具有构造函数、析构函数或任何其他类型的成员函数。它甚至可以有成员变量。

只需将构造函数添加到Parent即可。在Child中,您将调用Parent构造函数;构造函数调用不能"跳过一代"。

class Parent: public Grandparent
{
public:
  Parent(char const* string1, char const* string2):
    Grandparent(string1, string2)
  { }
  virtual int DoSomething() = 0;
};

如果您想要Parent的默认构造函数之外的其他东西,则需要提供它。

看看这个关于继承构造函数的问题

另外,请参阅这个抽象类的示例