【问题标题】:How do I implement a constructor that takes variables from its base class?如何实现从其基类获取变量的构造函数?
【发布时间】:2019-12-11 14:20:30
【问题描述】:

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

这是作业的说明:

基类 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 构造函数的参数。

除此之外,我还尝试在构造函数的开头和结尾打印一些东西。两者都显示在输出中,所以我确定构造函数运行了。

【问题讨论】:

  • “评分不通过”是什么意思?
  • @JohnZwinck 起初它只是说“不正确”而没有给我任何理由。现在我第二次提交,它指出了我的问题(但我仍然不明白这意味着什么以及我应该改变什么)

标签: c++ oop inheritance data-structures constructor


【解决方案1】:

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

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

... 这样Pair(a,b) 构造函数将在基类中被调用并正确设置基类变量。在您拥有的代码中,默认构造函数 Pair() 将被隐式调用,而基类的成员变量不会设置为 a 和 b。

【讨论】:

  • 你也可以像这样将 sum 添加到初始化列表中: sumPair::sumPair(int a, int b) : Pair(a, b), sum(a + b) {}。也许这是练习的一部分。
  • 谢谢,还有一个简单的问题:为什么基类初始化器是 Pair(a,b) 而不是 Pair(int a, int b)?
  • 因为在这段代码中你调用的是基类构造函数,所以它使用与任何其他函数调用相同的语法。
猜你喜欢
  • 2021-06-25
  • 2014-12-16
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
  • 2015-03-15
  • 2020-11-14
  • 1970-01-01
相关资源
最近更新 更多