C++基础题目:
题目:
超市商品编程题:
- 实现描述超市的的类 Suppermacket 类,记录系统中现有商品(用指针实现),定义增加商品的函数 Append ,删除商品的函数 Delete ,查询商品的函数 Query,并显示查询结果。
- 定义商品类 Goods ,具有商品名称Name,商品价格Price,商品数量number等属性,操作 Sale (销售商品,余额不足时给予提示)、Add(商品上架操作) 和ShowMe(显示商品信息)。
- 编写main函数,测试以上所要求的各种功能,完成商品的增加、删除和查询商品,以及商品销售和商品上架的操作。
- 可以利用对象成员来实现。
商品类Goods的定义
//Goods.h
#pragma once
#include <iostream>
using namespace std;
class Suppermacket;
class Goods
{
private: //定义私有函数
char Name[10];
int Price;
int number;
public: //定义共有函数
Goods()
{
Price = 0;
number = 0;
}
void Sale(int n);
void Add();
void ShowME()
{
cout << "商品:" << Name << ",价格:" << Price << ",数量:" << number << "件。\n\n";
};
friend Suppermacket; //定义友元函数
};
商品类Goods 的实现
//Goods.cpp
#include "Goods.h"
void Goods::Sale(int n) //调用销售商品函数
{
if (n < number)
{
number -= n;
ShowME();
}
else
cout << "商品数量不够,无法销售!\n";
}
void Goods::Add() //调用上架商品函数
{
cout << "商品上架:\n 请输入上架的商品名称、价格及数量:\n";
cin >> Name >> Price >> number;
}
超市类Suppermacket的定义
//Suppermacket.h
#pragma once
#include "Goods.h"
class Suppermacket
{
Goods* PGoods;
int num;
public:
Suppermacket(int n = 10)
{
PGoods = new Goods[n];
num = n;
}
void Append(); //定义增加商品的函数
void Delete(); //删除商品的函数
void Query(); //查询商品的函数
~Suppermacket()
{
delete[]PGoods;
}
};
超市类Suppermacket的实现
//Suppernacket.cpp
#include "Suppermacket.h"
void Suppermacket::Append() //增加商品的函数
{
for (int i = 0; i < num; i++)
{
if (PGoods[i].number == 0)
{
PGoods[i].Add();
PGoods[i].ShowME();
return;
}
}
cout << "没有空货架上货了!\n";
}
void Suppermacket::Delete() //删除商品的函数
{
char name[10];
int n;
cout << "商品出售:\n 请输入需要销售商品名称和数量:";
cin >> name >> n;
for (int i = 0; i < num; i++)
{
if (strcmp(PGoods[i].Name, name) == 0)
{
PGoods[i].Sale(n);
return;
}
}
cout << "查无此商品!\n";
}
void Suppermacket::Query() //查询商品的函数
{
char name[10];
cout << "商品查询:\n 请输入需要查询的商品名称:";
cin >> name;
for (int i = 0; i < num; i++)
{
if (strcmp(PGoods[i].Name, name) == 0)
{
PGoods[i].ShowME();
return;
}
}
cout << "查无此商品!\n";
}
主函数:
//主函数.cpp
#include <iostream>
#include "Goods.h"
#include "Suppermacket.h"
int main()
{
Suppermacket A(3); //调用类
A.Append();
A.Append();
A.Delete();
A.Query();
}