求一个C++程序 用类来写 越简单越好 在线等 急

2025-04-06 15:44:02
推荐回答(1个)
回答1:

#include
#include
using namespace std;
class CBook
{
public:
 CBook(){}
 void Init(string name, int count, float price)
 {
  m_name = name;
  m_count = count;
  m_price = price;
 }
 void ShowBookInfo()
 {
  cout << m_name << "\t" << m_count << "\t" << m_price << endl;
 }
 //书的属性为private,所以要提供对外呈现的接口
 string GetBookName()
 {
  return m_name;
 }
 int GetBookCount()
 {
  return m_count;
 }
 float GetBookPrice()
 {
  return m_price;
 }
private:
 string m_name;
 int m_count;
 float m_price;
};
class CBookMgr
{
public:
 //初始书类别数为0
 CBookMgr()
 {
  m_count = 0;
 }
 void ShowBooks()//显示书信息
 {
  int i;
  for(i = 0; i < m_count; ++i)
  {
   m_list[i].ShowBookInfo();
  }
 }
 void SearchBook(string name)//检索书名
 {
  class CBook* result = GetBook(name);
  if(!result)
  {
   cout << "book non-exist!" << endl;
  }
  else
  {
   cout << "book count is " << result->GetBookCount() << endl;
  }
 }
 void CheckPrice(string name, int count)//计算总价
 {
  class CBook* result = GetBook(name);
  if(!result || count < 0)
  {
   cout << "book info error!" << endl;
  } 
  else
  {
   cout << "total price is " << result->GetBookCount() * result->GetBookPrice() << endl;
  }
 }
 void AddBook(string name, int count, float price)//增加新书
 {
  m_list[m_count].Init(name,count,price);
  ++m_count;
 }
public:
 class CBook* GetBook(string name)
 {
  int i;
  
  for(i = 0; i < m_count; ++i)
  {
   if(name == m_list[i].GetBookName())
   {
    return &m_list[i];
   }
  }
  
  return NULL;
 }
private:
 class CBook m_list[10000];//简单起见,最多存储10000种书
 int m_count;//书的总类别数
};