繁体   English   中英

继承构造函数:从C#转换为C ++

[英]Inheritance constructors: Converting from C# to C++

我来自C#背景,我会写一个类和构造函数,如下所示:

public class Grunt : GameObject
{
    public Grunt()
        : base()
    {
         // do stuff
    }
}

如何在C ++中编写构造函数继承? 在标题和源中。 我知道你没有'base'关键字可以使用,但其他语法是否相同?

class Grunt : public GameObject
{
    Grunt()
        : GameObject()  // Since there are no parameters to the base, this line is actually optional.
    {
         // do stuff
    }
}

并强烈考虑在The Definitive C ++ Book Guide and List中获得一本优秀的C ++书籍

是的,将: base()替换为: GameObject()

但是如果没有参数,那么隐含了一个参数,就像在C#中一样

您使用基类的名称代替'base'关键字。 这是必要的,因为C ++中有多重继承的可能性。 如果有多个基类,您可以通过逗号分隔调用来调用多个基本构造函数。

标题:

template <int unique>
class base { 
public: 
    base();
    base(int param);
};

class derived: public base<1>, public base<2> {
public:
    derived();
    derived(int param);
};

资源:

base::base() 
{}

base::base(int param) 
{}

derived::derived() 
: base<1>()
, base<2>() 
{}

derived::derived(int param) 
: base<1>(param)
, base<2>(param) 
{}

这阐明了如何从多个类继承,从模板类继承,构造基类,演示如何将参数传递给基础构造函数,以及说明为什么我们必须使用基类的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM