难题求帮助2
编写一个程序以实现以下功能:(1)定义一个商品类Goods,包含数据成员:商品名称Name,商品价格Price,商品数量amount等;
包含如下主要成员函数:
>构造函数(用来初始化一个商品对象);
>销售商品Sale(商品余量不足时给予提示,若购买数量合法则显示应付款);
>商品上架Add;
>显示商品形象ShowMe。
(2)重载输出操作符<<实现Goods类对象的输出。
(3)编写main函数,测试以上所要求的各种功能。
要求C++实现。
急用,在线等!
#include <string>
#include <iostream>
using namespace std;
class Goods {
public:
Goods( string name, double price, int amount )
:Name(name),Price(price),Amount(amount){}
void Sale( int number );
void Add( int number ) { Amount += number; }
ostream& ShowMe( ostream& out ) const;
private:
string Name;
double Price;
int Amount;
};
void Goods::Sale( int number ) {
if( number>Amount ) {
cout<<"仅有"<<Amount<<"件商品"<<endl;
return;
}
Amount -= number;
cout<<"应付钱:"<<number*Price<<endl;
}
ostream& Goods::ShowMe( ostream& out ) const{
out<<"商品名称:"<<Name<<"\t单价:"<<Price<<"库存:"<<Amount;
return out;
}
ostream& operator<<( ostream& out, const Goods& goods ) {
return goods.ShowMe(out);
}
int main() {
Goods goods("程序作业", 20.5, 3);
cout<<goods<<endl;
goods.Sale(100);
goods.Sale(2);
cout<<goods<<endl;
goods.Add(10);
cout<<goods<<endl;
} #include <string>
#include <iostream>
using namespace std;
class Goods {
public:
Goods( string name, double price, int amount )
:Name(name),Price(price),Amount(amount){}
void Sale( int number );
void Add( int number ) { Amount += number; }
ostream& ShowMe( ostream& out ) const;
private:
string Name;
double Price;
int Amount;
};
void Goods::Sale( int number ) {
if( number>Amount ) {
cout<<"仅有"<<Amount<<"件商品"<<endl;
return;
}
Amount -= number;
cout<<"应付钱:"<<number*Price<<endl;
}
ostream& Goods::ShowMe( ostream& out ) const{
out<<"商品名称:"<<Name<<"\t单价:"<<Price<<"库存:"<<Amount;
return out;
}
ostream& operator<<( ostream& out, const Goods& goods ) {
return goods.ShowMe(out);
}
int main() {
Goods goods("程序作业", 20.5, 3);
cout<<goods<<endl;
goods.Sale(100);
goods.Sale(2);
cout<<goods<<endl;
goods.Add(10);
cout<<goods<<endl;
}
页:
[1]