gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:02:20 24 4
gpt4 key购买 nike

我正在做一个在线类(class),要求我按照我写的标题去做。我做了使代码编译并给出正确输出的操作,但是我评分中的评论给出了一个我不太明白的错误。

这是作业的说明:

A base class Pair contains a single constructor Pair(a,b) that initializes the pair with the two integer arguments a and b. A derived class sumPair inherits the base class Pair, and specializes it with a new constructor sumPair(a,b) and a new variable sum.

Both of these classes have already been defined.

Implement the new constructor sumPair(a,b), which was declared already in class sumPair. The new constructor sumPair(a,b) should initialize the inherited class Pair with integer values a,b and set the member variable "sum" to the sum of a and 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 我认为应该是正确的。

评分的错误是

The members of Pair were not properly initialized to the arguments of the sumPair constructor.

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

最佳答案

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

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

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

关于c++ - 如何实现从其基类获取变量的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com