【发布时间】: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