设计一个产品类Prodyct,其定义如下: class Product { char *name; //飞机票名称 int price; //单价 int quantity; //剩余机票的数量 Publice: product(char *n,int p,int q); //构造函数 ~product (); //析构函数 void buy (int money); //购买产品 void get () const; //显示剩余机票数量 }; 程序如下: #include <iostream.h> #include <string.h> class Product { char *name; //飞机票名称 int price; //单价 int quantity; //剩余机票的数量 Publice: product(char *n,int p,int q) { name=new char[strlen(n)+1]; strcpy (name,n); price=p; quantity=q; } ~product () { if (name) { delete [] name; name=0; } } void buy (int money) { int n,r; n=money/price; if (n>quantity) cout<<"数量不够!"<<endl; else { quantity-=n; r=money%price; cout<<"飞机票名称:"<<name<<"单价:"<<price<<"元 顾客"; cout<<money<<"元,买了"<<n<<"张,剩余"<<r<<"元"<<endl; } } void get() const { cout<<"飞机票名称:"<<name<<"单价:"<<price<<"元 剩余"<<quantity<<"张"<<endl; } }; void main() { Product p1("上海到纽约",2000,15); p1.buy(7000); p1.get(); p1.buy(4500); p1.get; } 执行结果如下: 飞机票名称:上海到纽约 单价:2000 顾客7000元,买了3张,剩余1000元 飞机票名称:上海到纽约 单价:2000 剩余12张 飞机票名称:上海到纽约 单价:2000 顾客4500元,买了2张,剩余500元 飞机票名称:上海到纽约 单价:2000 剩余10张 好象哪里怪怪的,等我考完试再写个吧!! [此贴子已经被作者于2003-12-31 13:02:18编辑过]
|