继承类的默认构造函数

继承类的默认构造函数

本文介绍了继承类的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将问题简化为以下示例代码:

I've reduced my problem down to the following example code:

class pokemon{
    public:
        pokemon(int n);
};

class MewTwo : public pokemon {
    public:
        MewTwo(int n);
};

MewTwo::MewTwo(int n) {}

错误:

我认为发生的是,当我尝试写入MewTwo构造函数时,会调用pokemon的默认构造函数,它不存在。我对C ++相对较新,所以我只是猜到这里。任何想法?

What I think is happening is that a default constructor for pokemon is called when I try to write the MewTwo constructor, which doesn't exist. I'm relatively new to C++ so I'm just guessing here. Any ideas?

Restraint:修复不能修改或添加公共成员到类。

Restraint: Fixes cannot modify or add public members to the classes.

推荐答案

实际上你正在寻找的是成员初始化列表。将您继承的类构造函数更改为以下类型:

Actually what you are looking for is the member initialization list. Change your inherited class constructor to the following:

class MewTwo : public pokemon {
    public:
        MewTwo(int n) : pokemon(n) {}
};

您确定发生了什么是正确的。基本上当你创建继承的类,你首先创建基类,你不能这样做,因为没有定义默认构造函数。成员初始化列表可帮助您解决此问题:)

You were correct in identifying what was going on. Basically when you create the inherited class you first create the base class and you can't do that because there is no default constructor defined. Member initialization lists help you get around that :)

签出:了解更多示例!

这篇关于继承类的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 18:10