【问题标题】:Constructor Definition with Inheritance带继承的构造函数定义
【发布时间】:2023-03-18 14:09:01
【问题描述】:

我的教授给出了以下代码来展示继承的示例:

//Base class
class Inventory {
    int quant, reorder; // #on-hand & reorder qty
    double price; // price of item
    char * descrip; // description of item
public:
    Inventory(int q, int r, double p, char *); // constructor
    ~Inventory(); // destructor
    void print();
    int get_quant() { return quant; }
    int get_reorder() { return reorder; }
    double get_price() { return price; }
};
Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p)
{
    descrip = new char[strlen(d)+1]; // need the +1 for string terminator
    strcpy(descrip, d);
} // Initialization list



//Derived Auto Class
class Auto : public Inventory {
    char *dealer;
public:
    Auto(int q, int r, double p, char * d, char *dea); // constructor
    ~Auto(); // destructor
    void print();
    char * get_dealer() { return dealer; }
};
Auto::Auto(int q, int r, double p, char * d, char * dea) : Inventory(q, r, p, d) // base constructor
{
    dealer = new char(strlen(dea)+1); // need +1 for string terminator
    strcpy(dealer, dea);
}

我很困惑“Auto::Auto(int q, int r, double p, char * d, char * dea) : Inventory(q, r, p, d)”,“Inventory( q, r, p, d)" 做。相似地 在“Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p)”行中,我不确定他在用 quant 做什么( q)、重新排序 (r)、价格 (p)。这些变量是否与在类中定义为 int quant、reorder 和 double price 的变量相同?如果是这样,为什么他必须在构造函数中使用。以及他为什么/如何使用基类的构造函数来帮助定义“Auto”类构造函数。

【问题讨论】:

  • 我看到这不是你的代码,但我认为值得一提的是这段代码非常丑陋,我认为不调用类 Auto 是一个非常好的主意语言中的auto 关键字。同样使用 char * 似乎是在 c++ 中执行此操作的一种非惯用方式,在几乎所有情况下,使用 std::string 都是一种更好的处理方式。

标签: c++ class object constructor


【解决方案1】:

他正在使用“初始化列表”。

他正在调用基类构造函数。 Auto::Auto(int q, int r, double p, char * d, char * dea) : Inventory(q, r, p, d)Auto 类定义了一个构造函数,它调用Inventory 的参数化构造函数。需要调用参数化构造函数,因为Auto 继承自Inventory 并且Inventory 定义了参数化构造函数。 C++ 规定,如果您定义参数化构造函数,则默认构造函数将被覆盖,并且您可以实例化该类或任何子类的对象的唯一方法是调用参数化构造函数(或通过定义备用默认构造函数)。

Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p) 的情况下,他分别用值qrp 初始化字段quantreorderprice。这实际上是一种简写,您可以改为在构造函数主体中分配值(除非该成员是常量)。

【讨论】:

  • 为什么他需要调用“Inventory(q, r, p, d)”。线路有什么作用?而且我在 Auto 的构造函数中看不到任何需要 Inventory 的参数化构造函数的东西。是为了“以防万一”吗
  • 他从不定义“Inventory”变量,因此从不实例化它。但是,他调用“Auto car(3, 1, 8745.99, "Four-Door", "GM")。这是否会因为 Auto 中的构造函数定义而自动调用 Inventory 构造函数,从而初始化 "quant" 的值,"重新排序”、“价格”和“d”。
  • 如果Auto 的构造函数以某种方式调用Inventory 的参数化构造函数,您只能实例化Auto 类型的对象,因为它从它继承。所以根据OOP的原理,一个Auto对象就是一个Inventory对象。
  • 所以既然他实例化了 Auto,他就不需要实例化 Inventory。但是如何设置“quant”、“reorder”、“price”和“d”的私有成员值,它们用作 Inventory 的构造函数。他们怎么称呼?
  • 当您像这样调用Inventory 的参数化构造函数时:Inventory(q, r, p, d),它会为您执行此操作。 Inventory 的构造函数就是这样做的。
【解决方案2】:

在子构造函数中,你总是默认调用父构造函数。如果该构造函数接收参数,则必须使用 : 表示法显式编写调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2013-06-01
    • 2023-04-03
    • 2015-06-21
    相关资源
    最近更新 更多