派生类中的基本构造函数调用 [英] Base Constructor Call in Derived Class

查看:111
本文介绍了派生类中的基本构造函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在大学的家庭作业中遇到以下问题,任务如下:

I have got the following problem in a homework for university, the task is as follows:

派生班级 MyThickHorizo​​ntalLine 来自 MyLine 。一个要求是派生类 MyThickHorizo​​ntalLine 的构造函数本身不设置值,而是必须调用基础构造函数。

Derive a class MyThickHorizontalLine from MyLine. One requirement is that the constructor of the derived class MyThickHorizontalLine does not set the values itself, instead its obligated to call the base constructor.

目前在我的cpp文件中看起来像这样:

Which currently looks like this in my cpp file:

MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c)
{
    MyLine(a, b, c, b);
}

这是我的Base构造函数:

This is my Base constructor:

MyLine::MyLine(int x1, int y1, int x2, int y2)
{
    set(x1, y1, x2, y2);
}

MyLine的标题定义:

Header Definition of MyLine:

public:
    MyLine(int = 0, int = 0, int = 0, int = 0);

目前的问题是,当我调试这个时,我会进入 MyThickHorizo​​ntalLine的构造函数 的价值 b c 例如 1 2 3 它们被设置那时,当我进一步进入Base构造函数时,我的所有值都为零。

Current problem is that when I debug this I step into the constructor of MyThickHorizontalLine my values for a b c are for example 1 2 3 they are set there and when I then step further and it gets into the Base constructor all my values are Zero.

我可能在这里遗漏了关于继承的关键部分,但我可以'让我明白。

I am probably missing a crucial part about inheritance here, but I can't get my mind on it.

推荐答案


MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c)
{
     MyLine(a, b, c, b); // <<<< That's wrong
}


你无法初始化你的基类在构造函数体内。只需使用成员初始化列表来调用基类构造函数:

You cannot initialize your base class inside the constructor's body. Simply use the member initializer list to call the base class constructor:

MyThickHorizontalLine::MyThickHorizontalLine(int a, int b, int c) : MyLine(a, b, c, b) {}

这篇关于派生类中的基本构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆