我的教授给出了以下代码来展示继承的示例:
//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 的变量相同?如果是这样,为什么他必须在构造函数中使用。以及他为什么/如何使用基类的构造函数来帮助定义“自动”类构造函数。