4128人加入学习
(13人评价)
C++编程系列 第二季函数和类

制作于2018.4.2

价格 免费

习题4

完成程序:药品物资管理

要求:

1.利用结构体来存储目前拥有的药物的名称、种类、数量、买入价格、卖出价格。

2.利用枚举来设置药物的种类(回复mp和回复hp)。

3.编写函数来控制药物的买入和卖出,卖出价为买入价格的3/4。

4.编写函数来显示拥有的药物的剩余钱数。

5.通过输入数字来控制函数调用。

6.实现分离式编译。

 

习题5

完成程序:药品物资管理

要求:

1.创建药品类完成习题4中对药品相关的管理。

2.利用对象数组来完成对不同种类药品的信息的存储。

3.使用*this指针。

4.使用作用域为类的常量。

 

//Drugs.h

#pragma once
#ifndef DRUGS_H_
#define DRUGS_H_

#include <string>
using namespace std;

enum Type { PlusHP, PlusMP };

class Drugs
{
private:
	string name_;
	Type type_;
	int count_;
	float buyPrice_;
	float sellPrice_;
	static constexpr float Ratio = 0.75f;
public:
	Drugs(string name, Type type, int count, float buyPrice);
	Drugs();
	~Drugs();
	void buyDrug(float &money, int num);
	void sellDrug(float &money, int num);
	void showDrug();
	string showType();
};

#endif // !DRUGS_H_

//Drugs.cpp

#include "pch.h"
#include "Drugs.h"
#include <iostream>

Drugs::Drugs(string name, Type type, int count, float buyPrice)
{
	name_ = name;
	type_ = type;
	count_ = count;
	buyPrice_ = buyPrice;
	sellPrice_ = buyPrice * Ratio;
}

Drugs::Drugs()
{
}


Drugs::~Drugs()
{
}

void Drugs::buyDrug(float & money, int num)
{
	if (num > 0)
	{
		if (buyPrice_ * num <= money)
		{
			money -= buyPrice_ * num;
			count_ += num;
			cout << "购买成功!!!" << endl;
		}
		else
		{
			cout << "警告:您的钱不够买" << num << "个药物!!!" << endl;
		}
	}
	else
	{
		cout << "警告:输入有误!!!" << endl;
	}
}

void Drugs::sellDrug(float & money, int num)
{
	if (num > 0)
	{
		if (num <= count_)
		{
			count_ -= num;
			money += sellPrice_ * num;
			cout << "卖出成功!!!" << endl;
		}
		else
		{
			cout << "警告:您没有" << num << "个药物可以卖出!!!" << endl;
		}
	}
}

void Drugs::showDrug()
{
	cout << "药物名称:" << name_ << "  数量:" << count_ << "  种类:" << type_ << "  买入价格:" << buyPrice_
		<< "卖出价格:" << sellPrice_ << endl;
}

string Drugs::showType()
{
	if (type_ == 0)
	{
		return "PlusHP";
	}
	else
	{
		return "PlusMP";
	}
}

[展开全文]