具有继承的构造函数定义

Jos*_*osh 0 c++ constructor class object

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

//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);
}
Run Code Online (Sandbox Code Playgroud)

我很混淆行"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"类构造函数.

Sid*_*gal 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),他正在初始化等领域quant,reorderprice与价值观q,rp分别.这实际上是一种简写,您可以在构造函数体中指定值(除非成员是常量).