我正在做一个在线课程,要求我做我写的标题。我做了什么使代码编译并给出正确的输出,但是我在评分中的注释给出了一个我不太了解的错误。
这是作业的说明:
基类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设置为a
和b
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句