【发布时间】: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