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

标签 c++ inheritance

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

class Grandparent {
    public:
        Grandparent(const char*, const char*);
};

class Parent : public Grandparent {
    public:
        virtual int DoSomething() = 0;
};

祖 parent 的构造函数有两个参数。我希望我的子类 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 的构造函数?

最佳答案

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

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

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

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

关于c++ - 通过抽象类将参数传递给祖父类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9475477/

相关文章:

Javascript - 从原型(prototype)方法内部调用子方法

Django:为可重用的模型字段创建 Mixin

java - Java中的继承,访问子方法并使用父类数组

c++ - 从一个字节数组中打印出 26 个字节

C++ 没有初始化变量

c++ - QT4中slots如何使用自定义函数

c++ - 常量类型定义;在 C 和 C++ 中

c++ - 如何声明一个指向 int 数组的指针数组?

java - 面向对象 : inheritance with extends

c++ - 继承实际上是如何工作的?