gpt4 book ai didi

c++ - 继承构造函数输出

转载 作者:行者123 更新时间:2023-11-30 05:34:19 25 4
gpt4 key购买 nike

#include <iomanip>
#include <iostream>
#include <string>
using namespace std;

class Box
{
protected:
double length;
double width;
double height;
public:
// Constructors
Box(double lv, double wv, double hv) : length {lv}, width {wv}, height {hv}
{ std::cout << "Box(double, double, double) called.\n"; }

Box(double side) : Box {side, side, side}
{ std::cout << "Box(double) called.\n"; }

Box() { std::cout << "Box() called.\n"; }

double volume() const
{ return length * width * height; }

double getLength() const { return length; }
double getWidth() const { return width; }
double getHeight() const { return height; }
~Box()
{ cout << "box destructor" << endl; }
};


class Carton : public Box
{
private:
string material {"Cardboard"};
public:
Carton(double lv, double wv, double hv, const string desc) : Box {lv, wv, hv}, material {desc}
{ std::cout << "Carton(double,double,double,string) called.\n"; }

Carton(const string desc) : material {desc}
{ std::cout << "Carton(string) called.\n"; }

Carton(double side, const string desc) : Box {side},material {desc}
{ std::cout << "Carton(double,string) called.\n"; }

Carton() { std::cout << "Carton() called.\n"; }

~Carton()
{ cout << "carton destructor" << endl; }
};

int main()
{
Carton carton3 {4.0, "Plastic"};
}

在这段代码中,我期望输出

Box(double) called.
Carton(double,string) called.
cartoon destructor
box destructor

但它显示为输出

Box(double, double, double) called.
Box(double) called.
Carton(double,string) called.
cartoon destructor
box destructor

我不明白 Box(double, double, double) called. 是如何显示在屏幕上的。我已逐步跟踪代码,但它不能出现在输出中。有人可以解释这个问题吗?谢谢。

最佳答案

这一行

Carton(double side, const string desc) : Box {side},material {desc}

表示将调用构造函数Box::Box(double side)。但是,该构造函数定义为:

Box(double side) : Box {side, side, side} // HERE is the call to second constructor
{ std::cout << "Box(double) called.\n"; }

这意味着它将依次调用构造函数Box::Box(double lv, double wv, double hv)。您所描述的行为是预期的。在线下断点:

{ std::cout << "Carton(double,double,double,string) called.\n"; }

你会看到当你运行程序时它会被命中。

关于c++ - 继承构造函数输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34292766/

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