Request:
编写一个Book类,包含name(书名)、writer(著者)、public_name(出版社)、price(价格)、number(数量)、NO(书号)等数据成员。定义成员函数setBook,用来为书籍的数据成员赋值,定义成员函数borrow和restore,分别办理借出和还回(借、还书时,暂时只完成数量的增1减1,这里的书仍是一种书的概念,随着课程进展,我们继续做真正的图书管理系统,每本书都能追踪到是谁何时借了,何时还了)业务,定义成员函数print用于输出—有关书的信息,定义set_NO与get_NO来实现修改类对象的书号与获得类对象的书号。自己写main函数,用来测试你编写的类。
#include <iostream>
using namespace std;
#include "head.h"
int main(){
Book B1, B2;
B1.setBook();
B2.setBook();
cout<<"重置第一本书的书号:";
B1.set_NO();
B1.get_NO();
B1.borrow(5);
B1.getBook();
B2.restore(6);
B2.getBook();
return 0;
}
#ifndef HEAD_H_INCLUDED
#define HEAD_H_INCLUDED
class Book{
private:
string name;
string writer;
string pulic_name;
double price;
int number;
string NO;
public:
void setBook();
void getBook();
void borrow(int);
void restore(int);
void set_NO();
void get_NO();
};
#endif // HEAD_H_INCLUDED
#include <iostream>
using namespace std;
#include "head.h"
void Book::setBook(){
string setName, setWriter, setPulicName, setNO;
double setPrice;
int setNumber;
cout<<"书名: ";
getline(cin,setName);
cout<<"作者: ";
getline(cin,setWriter);
cout<<"出版商:";
getline(cin,setPulicName);
cout<<"价格: ";
cin>>setPrice;
cout<<"数量: ";
cin>>setNumber;
cout<<"书号: ";
cin>>setNO;
name=setName;
writer=setWriter;
pulic_name=setPulicName;
price=setPrice;
number=setNumber;
NO=setNO;
cout<<endl;
cin.ignore();
}
void Book::getBook(){
cout<<"该书信息如下:"<<endl;
cout<<"书名: "<<name<<endl;
cout<<"作者: "<<writer<<endl;
cout<<"出版商:"<<pulic_name<<endl;
cout<<"价格: "<<price<<endl;
cout<<"数量: "<<number<<endl;
cout<<"书号: "<<NO<<endl<<endl;
}
void Book::set_NO(){
string newNO;
cin>>newNO;
NO=newNO;
}
void Book::get_NO(){
cout<<"该书书号为:"<<NO<<endl<<endl;
}
void Book::borrow(int i){
if (i>number)
cout<<"最多可借"<<number<<"本"<<endl;
else{
cout<<name<<"借出"<<i<<"本"<<endl;
number-=i;
}
}
void Book::restore(int j){
cout<<name<<"返还"<<j<<"本"<<endl;
number+=j;
}
Result:
Gain:
void Book::setBook(){
string setName, setWriter, setPulicName, setNO;
double setPrice;
int setNumber;
cout<<"书名: ";
getline(cin,setName);
...
...
...
cin.ignore();
}
解决了两次调用getline()只能输出一次的问题