2011-10-05 48 views
3

我从一个C#的背景,我会写的类和构造这样的未来:继承构造函数:从C#转换为C++

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

我怎样写C++中的构造函数继承?在标题和来源中。我知道你没有使用“基本”关键字,但其他语法是否一样?

回答

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

,并强烈考虑购买的精C++的书之一,在The Definitive C++ Book Guide and List

+0

'在标题和源文件中.' –

5

是,与: GameObject()更换: base()

但是,如果没有参数,调用是隐含的,如C#

3

你在的地方“基地”关键字的使用基类的名称。这是必要的,因为C++中有多重继承的可能性。在多个基类的情况下,可以通过逗号分隔调用来调用多个基类构造函数。

1

头:

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) 
{} 

这澄清了如何从多个类继承,从模板类继承,构造基类,示出了如何将参数传递到基础构造,和显示为什么我们必须使用基地的名称。