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

来源:互联网 发布:高精度电子罗盘软件 编辑:程序博客网 时间:2024/05/22 01:35
题目描述:
编写一个程序,设计一个产品类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; }


输出:




2 0
原创粉丝点击