我有一个由图书馆提供的类 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/