题目:定义一个图书类Book和一个读者类Reader,实现读者借阅图书,图书能记录当前总馆藏记录数,剩余馆藏数和总借阅次数。
要求:
- 程序具有健壮性,例如剩余馆藏数不足的时候不能借阅;
- 多次添加(创建新的图书类)、借阅图书(调用读者类的borrow方法),并依次打印出当前总馆藏记录数,剩余馆藏数和总借阅次数等结果。
- 静态数据成员不属于任何一个对象,被类的所有对象共享,且需要在类定义之外再定义来分配空间。
- 图书类使用静态数据成员(私有)保存当前总馆藏记录数,剩余馆藏数和总借阅次数;读者类为图书类的友元类。
#include <iostream>
using namespace std;
class Book {
private:
int collections, remainder, borrowNum; //某本书的馆藏记录数,剩余馆藏数和借阅次数
static int library_Collections; //整个图书馆的总馆藏数
static int library_Remainder; //整个图书馆的剩余馆藏数
static int library_BorrowNum; //整个图书馆的图书借阅次数
public:
Book(int x);
void display();
friend class Reader; //读者类为图书类的友元类
};
Book::Book(int x) {
collections = x;
remainder = collections;
borrowNum = 0;
library_Collections += x; //每新增一种图书,就把该图书的数量加到图书馆总馆藏和图书馆剩余馆藏中
library_Remainder += x;
}
void Book::display() {
cout << "该书馆藏记录数:" << collections;
cout << "\t该书剩余馆藏数:" << remainder;
cout << "\t该书借阅次数:" << borrowNum << endl;
cout << "图书馆藏记录数:" << library_Collections;
cout << "\t图书馆剩余馆藏数:" << library_Remainder;
cout << "\t图书馆总借阅次数:" << library_BorrowNum << endl;
if (remainder > 0) {
cout << "此书可以继续借阅" << "\n" << endl;
}
else {
cout << "此书不可继续借阅" << "\n" << endl;
}
}
class Reader {
public:
Reader(int x);
void borrow(Book &b);
};
Reader::Reader(int x) {
cout << "一位读者来借" << x << "本书" << "\n" << endl;
}
void Reader::borrow(Book &b) {
if (b.remainder > 0) { //根据所借书的余量判断是否节约成功
cout << "此书借阅成功" << endl;
--b.remainder;
++b.borrowNum;
--b.library_Remainder;
++b.library_BorrowNum;
}
else {
cout << "此书馆藏不足,未能借阅" << endl;
}
}
int Book::library_Collections = 0;
int Book::library_Remainder = 0;
int Book::library_BorrowNum = 0;
int main()
{
cout << "图书1:" << endl;
Book b1 = Book(1);
b1.display();
cout << "图书2:" << endl;
Book b2 = Book(2);
b2.display();
Reader r = Reader(2);
r.borrow(b1);
cout << "图书1:" << endl;
b1.display();
r.borrow(b2);
cout << "图书2:" << endl;
b2.display();
Reader re = Reader(2);
re.borrow(b1);
cout << "图书1:" << endl;
b1.display();
re.borrow(b2);
cout << "图书2:" << endl;
b2.display();
return 0;
}
实际上运行结果在控制台里是交互的,写得比较乱,还请见谅。