2012-02-28 105 views
1

我有一个类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不能有一个构造函数,我怎样才能将这些值传递给祖父母的构造函数?

+0

为什么你认为'Parent'不能有一个构造函数? – 2012-02-28 02:22:30

回答

3

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

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

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

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

出于某种原因,我认为抽象类不能有构造函数。当然你的解决方案效果很好。谢谢! – bdesham 2012-02-28 05:56:46

+0

也许你正在考虑使用其他语言的* interfaces *,例如Java,C#或Delphi。 C++没有单独的接口类型。 – 2012-02-28 06:03:09

+0

是的,我来自Objective-C,我仍然在研究接口和抽象基类之间的差异。 – bdesham 2012-02-28 18:55:14

相关问题