通过抽象类将参数传递给祖父母类的构造函数
Passing arguments through an abstract class to the grandparent class’s constructor
我有一个由库提供的类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的默认构造函数之外的其他东西,则需要提供它。
看看这个关于继承构造函数的问题
另外,请参阅这个抽象类的示例
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 通过抽象类将参数传递给祖父母类的构造函数