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

发布于 2024-12-08 11:52:42 字数 259 浏览 0 评论 0原文

我有 C# 背景,我会编写如下所示的类和构造函数:

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

How do I write the constructorheritance in C++?在标题和源代码中。我知道您没有可以使用的“base”关键字,但是语法是否相同?

I'm coming from a C# background where I would write a class and constructor like this:

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

How do I write the constructors inheritance in C++? In both the header and the source. I know you don't have the 'base' keyword to work with, but otherwise is the syntax the same?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一城柳絮吹成雪 2024-12-15 11:52:42
class Grunt : public GameObject
{
    Grunt()
        : GameObject()  // Since there are no parameters to the base, this line is actually optional.
    {
         // do stuff
    }
}

强烈考虑在 权威 C++ 书籍指南和列表中获取一本优秀的 C++ 书籍

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

And strongly consider getting one of the fine C++ books at The Definitive C++ Book Guide and List

叫嚣ゝ 2024-12-15 11:52:42

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

但如果没有参数,则隐含调用,如 C# 中那样

Yes, replace : base() with : GameObject().

But if there are no parameters the call is implied, as in C#

奈何桥上唱咆哮 2024-12-15 11:52:42

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

You use the name of the base class in place of the 'base' keyword. This is necessary because of the possibility for multiple inheritance in C++. In the event of multiple base classes, you can call multiple base constructors by comma-delimiting the calls.

想你只要分分秒秒 2024-12-15 11:52:42

header:

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

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

source:

base::base() 
{}

base::base(int param) 
{}

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

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

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

header:

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

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

source:

base::base() 
{}

base::base(int param) 
{}

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

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

This clarifies how to inherit from multiple classes, inherit from template classes, construct base classes, shows how to pass parameters to base constructors, and shows why we have to use the name of the base.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文