如何实现从其基类中获取变量的构造函数?

帕特里夏·宋

我正在做一个在线课程,要求我做我写的标题。我做了什么使代码编译并给出正确的输出,但是我在评分中的注释给出了一个我不太了解的错误。

这是作业的说明:

基类Pair包含单个构造函数Pair(a,b),该构造函数使用两个整数参数a和b初始化该对。派生类sumPair继承基类Pair,并使用新的构造函数sumPair(a,b)和新的变量sum对其进行专用化。

这两个类均已定义。

实现新的构造函数sumPair(a,b),该构造函数已在类sumPair中声明。新的构造函数sumPair(a,b)应使用整数a,b初始化继承的类Pair,并将成员变量“ sum”设置为a和b的总和。

现在是代码(我只写了几行)

    /* Class Pair has already been
     * declared and defined with the
     * following constructor:
     *
     *   Pair(int,int)
     *
     * that stores its two arguments in
     * two private member variables of Pair.
     *
     * Class sumPair has also already been
     * defined as follows:
     *
     * class sumPair : public Pair {
     * public:
     *   int sum;
     *   sumPair(int,int);
     * };
     * 
     * Implement the constructor
     * sumPair(int,int) such that it
     * loads the two member variables of
     * the base Pair class with its
     * arguments, and initializes the
     * member variable sum with their sum.
     */

    //this is the part I wrote
    sumPair::sumPair(int a,int b){
      sum =a+b;
    }

    /* Below is a main() function
     * you can use to test your
     * implementation of the
     * sumPair constructor.
     */

    int main() {
      sumPair sp(15,16);
      std::cout << "sp(15,16).sum =" << sp.sum << std::endl;
      return 0;
    }

我得到输出sp(15,16).sum = 31,我认为应该是正确的。

评分的错误是

Pair的成员未正确初始化为sumPair构造函数的参数。

除此之外,我还尝试在构造函数的开头和结尾打印内容。两者也都显示在输出中,因此我确定构造函数已运行。

杰里米·弗里斯纳

您已sum正确初始化,但是忘记了调用基类构造函数。即您想要的是:

sumPair::sumPair(int a,int b)
  : Pair(a, b)
{
  sum =a+b;
}

...,以便Pair(a,b)构造函数将在基类中被调用并正确设置基类变量。在您拥有的代码中,将默认Pair()隐式调用default-constructor ,而不会将基类的member-variables设置为ab

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何通过使用C ++中的构造函数获取父类的变量来在子类中实现Abstarct类的方法

从实现类的构造函数中获取接口方法的实现

如何让子类中的构造函数继承构造函数或基类?

如何在派生类构造函数中初始化基类成员变量?

无法获取派生类以使用其基类的构造函数

如何从父类构造函数中获取变量并在子类中使用它?

如何从类中的函数中获取变量?

如何在源文件中实现嵌套类构造函数

调用基类构造函数而不命名其类

如何在Scala中从派生类辅助构造函数调用辅助基类构造函数?

在python中,实现其构造函数可能会失败的类的正确方法是什么?

如何在Javascript中重写基类构造函数

如何在多级继承中调用基类构造函数?

不知道扩展类的扩展类的c ++调用构造函数存储在基类变量中

如何比类中的成员变量更早地调用构造函数?

如何使.env变量在JS类构造函数中工作?

如何实现从某个来源提取的属性,直到直接在Kotlin中对其进行设置?

自动实现一个构造函数,该构造函数调用特定的基类构造函数

即使派生类没有成员变量,我是否需要重新实现基类的所有构造函数?

如何在通用构造函数中获取类名

派生类的构造函数可以比其基类的构造函数具有更多的参数吗?

构造函数获取内部通用类的实例作为其参数。如何使用它?

创建没有其构造函数参数的类变量

如何使用指向函数的指针在基类构造函数中调用派生类的方法?

如何从构造函数继承类变量类型?

如何从其构造函数中定义的HTML中调用类方法?

在构造函数中增加静态类变量

php:访问构造函数中的类变量

如何强制实现抽象类的类声明其变量?