C++面向对象类的实例题目二

题目描述:
编写一个程序,设计一个产品类Product,其定义如下:
class Product
{
	public:
		Product(char *n,int p,int q);	//构造函数
		~Product();						//析构函数
		void buy(int money);			//购买产品
		void get() const;				//显示剩余产品数量 
	private:
		char * name;	//产品名称
		int price;		//产品单价
		int quantity;	//剩余产品数量
}; 
并用数据进行测试。

code:

#include<iostream>
#include<cstring>
using namespace std;
class Product
{
		char *name;
		int price;
		int quantity;
	public:
		Product(char *n,int p,int q);
		~Product();
		void buy(int money);
		void get()const;
};
Product::Product(char *n,int p,int q)
{
	name = n;
	price = p;
	quantity = q;
}
Product::~Product()
{
}
void Product::buy(int money)
{
	int r,n;
	n = money/price;
	r = money%price;
	if(n > quantity)
	{
		cout<<"数量不够"<<endl;
	}
	else
	{
		quantity -= n;
		cout<<"名称:"<<name<<",单价:"<<price<<"元"<<endl;
		cout<<"顾客使用"<<money<<"元,购买"<<n<<"台,剩余"<<r<<"元"<<endl; 
	}
}
void Product::get()const
{
	cout<<"产品:"<<name<<",单价:"<<price<<",剩余:"<<quantity<<"台"<<endl; 
}
int main()
{
	Product p("Iphone6",100,20);
	p.buy(10);
	p.get();
	cout<<"\n==========================\n"<<endl; 
	p.buy(1000);
	p.get();
	return 0; 
}


输出:




posted @ 2013-12-31 15:43  千手宇智波  阅读(486)  评论(0编辑  收藏  举报