关于这个问题就是C++中类的应用(类的继承),也可以使用类中的友元类
第一步:
将图书跟读者的类分别写出来
class Book
{
public:
Book(string nam, int n, string w)
{
name = nam;
num = n;
writer = w;
}
string name;
int num;
string writer;
};
class person :public Book
{
public:
void print_person();
void display();
private:
string name_person;
int number;
Book book[5];
};
在这里用的类的继承,Book 定义5个数组
person : public Book ,我们就是要在person中通过数组来增加一个借阅书的属性(这里为了简便,就直接按每个人都借五本书)。
因为Book是类中定义,而Person类外定义,所以将类外定义的函数写出来
void person::print_person()
{
cout << "输入借阅人姓名";
cin >> name_person;
cout << "输入借阅人卡号";
cin >> number;
}
void person::display()
{
cout << "借阅人姓名:" << name_person << "借阅人卡号:" << number << endl;
cout << "书名:" << book[0].name << "序号:" << book[0].num << "作者:" << book[0].writer << endl;
cout << "书名:" << book[1].name << "序号:" << book[1].num << "作者:" << book[1].writer << endl;
cout << "书名:" << book[2].name << "序号:" << book[2].num << "作者:" << book[2].writer << endl;
cout << "书名:" << book[3].name << "序号:" << book[3].num << "作者:" << book[3].writer << endl;
cout << "书名:" << book[4].name << "序号:" << book[4].num << "作者:" << book[4].writer << endl;
}
现在 ,基本的类定义和继承已经完成。
主函数中,用person定义一个对象p1,来进行类函数的输出与输入
int main()
{
Book b1("活着", 1, "余华");
Book b2("战争与和平", 2, "列夫托尔斯泰");
Book b3("巴黎圣母院", 3, "雨果");
Book b4("童年", 4, "高尔基");
Book b5("老人与海", 5, "海明威");
Book b6("呼啸山庄", 6, "艾米勃朗特");
person p1;
p1.print_person();
p1.display();
}
写到这里,此道题就结束了,这只是咱们平常的想法。
但此时会有bug产生
如何解决呢