具有继承的构造函数定义

时间:2012-12-05 01:32:36

标签: c++ class object constructor

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

//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):库存(q,r,p,d)”,定义是什么“库存”( q,r,p,d)“做。同样 在行“Inventory :: Inventory(int q,int r,double p,char * d):quant(q),reorder(r),price(p)”我不确定他在做什么( q),重新订购(r),价格(p)。这些变量是否在类中定义为int quant,reorder和double price?如果是这样,为什么他必须在构造函数中使用。为什么/如何使用基类中的构造函数来帮助定义“Auto”类构造函数。

2 个答案:

答案 0 :(得分:5)

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

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

如果是Inventory::Inventory(int q, int r, double p, char * d) : quant (q), reorder (r), price (p),他正在使用值quantreorder初始化字段priceqr,分别为p。这实际上是一个简写,您可以在构造函数体中指定值(除非成员是常量)。

答案 1 :(得分:4)

在子构造函数中,默认情况下总是调用父的构造函数。如果该构造函数接收到参数,则必须使用:notation显式写入调用。