本关任务:假设某商店有如下几种货品:衬衣、帽子、立柜。每一种货物都有与其关联的说明信息。 衬衣:单价、产地、库存量、布料; 帽子:单价、产地、库存量、布料、样式(平顶或尖顶); 立柜:单价、产地、库存量、木料、颜色。 对这些商品的操作有:商品的进库(增加库存量),商品的出库(减少库存量),该类货品总价格的计算。要求自行设计数据结构,用类的继承与派生关系将上述的各种货品表示出来,并使用类的构造函数来初始化每一类对象的初始数据。
时间: 2023-07-10 10:42:38 浏览: 48
好的,我可以为您提供一个用类的继承与派生关系来表示衬衣、帽子和立柜的示例代码。以下是实现这个需求的代码:
```cpp
#include <iostream>
using namespace std;
class Goods {
protected:
double price; // 单价
string origin; // 产地
int stock; // 库存量
public:
Goods(double p, string o, int s): price(p), origin(o), stock(s) {}
virtual void showInfo() {
cout << "Price: " << price << endl;
cout << "Origin: " << origin << endl;
cout << "Stock: " << stock << endl;
}
virtual double totalPrice() {
return price * stock;
}
};
class Shirt: public Goods {
private:
string material; // 布料
public:
Shirt(double p, string o, int s, string m): Goods(p, o, s), material(m) {}
void showInfo() {
Goods::showInfo();
cout << "Material: " << material << endl;
}
};
class Hat: public Goods {
private:
string material; // 布料
string style; // 样式(平顶或尖顶)
public:
Hat(double p, string o, int s, string m, string st): Goods(p, o, s), material(m), style(st) {}
void showInfo() {
Goods::showInfo();
cout << "Material: " << material << endl;
cout << "Style: " << style << endl;
}
};
class Cabinet: public Goods {
private:
string wood; // 木料
string color; // 颜色
public:
Cabinet(double p, string o, int s, string w, string c): Goods(p, o, s), wood(w), color(c) {}
void showInfo() {
Goods::showInfo();
cout << "Wood: " << wood << endl;
cout << "Color: " << color << endl;
}
};
int main() {
Shirt s(100, "China", 50, "Cotton");
Hat h(60, "USA", 80, "Wool", "Flat Top");
Cabinet c(500, "China", 10, "Oak", "Brown");
cout << "Shirt Information:" << endl;
s.showInfo();
cout << "Total Price: " << s.totalPrice() << endl << endl;
cout << "Hat Information:" << endl;
h.showInfo();
cout << "Total Price: " << h.totalPrice() << endl << endl;
cout << "Cabinet Information:" << endl;
c.showInfo();
cout << "Total Price: " << c.totalPrice() << endl << endl;
return 0;
}
```
在这段代码中,Goods是货品类,包含了单价、产地和库存量三个属性,并提供了showInfo和totalPrice函数用于输出和计算货品信息。
Shirt、Hat和Cabinet都是继承自Goods的子类,它们分别添加了特定的属性,并重写了showInfo函数以输出完整的货品信息。同时,由于Hat和Cabinet有特定的属性,所以它们还需要重写totalPrice函数以计算总价格。
在main函数中,我们创建了一个衬衣对象s、一个帽子对象h和一个立柜对象c,并分别输出它们的信息和总价格。