当前位置: 首页 > 工具软件 > book > 使用案例 >

定义一个图书类(Book)

邢焱
2023-12-01

定义一个图书类(Book),数据成员包括:书名、作者、单价、数量;成员函数包括:借书、还书、显示;借书时判断数量,如果数量为0输出书名借阅失败,如果数量大于0,数量减1并输出书名和剩余数量。还书时数量加1并输出书名和剩余数量。显示时能够输出图书的所有信息。创建图书对象时,可以给出书名、作者、单价、数量的数据进行初始化;也可以不给出任何数据,此时图书的书名是未命名,作者是佚名,单价是0,数量是0。在主函数中创建图书对象book1和book2,book1初始化为“人类简史”、赫拉利、68、10。book2不初始化。然后分别输出book1和book2的信息。book1借书2次,book2借书1次,还书1次,最后再分别输出book1和book2的信息。

#include <string.h>
#include <iostream>
using namespace std;
class Book
{
public:
 Book(string book, string writer, int num, int money);
 Book();
 void bring();
 void ret();
 void show();
private:
 string book;
 string writer;
 int num;
 int money;
};
Book::Book(string book, string writer, int num, int money)
{
 this->book = book;
 this->writer = writer;
 this->num = num;
 this->money = money;
}
Book::Book()
{
 book = "未命名";
 writer = "佚名";
 num = 0;
 money = 0;
}
void Book::bring()
{
 if (num <= 0)
  cout << "借阅失败";
 else
  num--;
 cout << book << "剩余" << num << "本" << endl;
}
void Book::ret()
{
 num++;
 cout << book << "剩余" << num << "本" << endl;
}
void Book::show()
{
 cout << book << "作者:" << writer << money << "剩余" << num << "本" << endl;
}
int main()
{
 Book book1("人类简史", "赫拉利", 68, 10);
 Book book2;
 book1.show();
 book2.show();
 book1.bring();
 book1.bring();
 book2.bring();
 book2.ret();
 book1.show();
 book2.show();
 return 0;
}
 类似资料: