#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.
的。我已经逐步跟踪代码,但它不能在输出上。有人可以解释这个问题吗?感谢。
答案 0 :(得分:1)
这一行
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"; }
你将看到它在运行程序时会被点击。