要求
定义一个Book类,在int main中,要求创建一个图书对象,并对该图书进行简单的显示、借阅、归还管理。
#include<iostream>
#include<cstring>
using namespace std;
class Book
{public:
static int number;
Book(char a,double b); //错误1
void display();
void borrow();
void restore(){number++;}
private:
char bookname; //错误1
double price;
};
Book::number=0; //错误4
Book::Book(char a,double b){ //错误1
strcpy(bookname,a); //错误2
price=b;
number++;}
void Book::borrow() { number--; cout<<"图书数量"<<number;}
void display(){cout<<"书名 ;"<<bookname<<" 价格"<<price<<endl;} //错误3
int main(){
Book a("资治通鉴",78.9);
a.display();
a.borrow();
a.restore();
}
错误展示:
错误明示
1.字符串的定义错误 char bookname
改为char* bookname
2.但是这样也不能显示原因在于没有给书名开辟空间;在错误2加入
bookname=new char[strlen(a)+1];strcpy(bookname,a);
3.没有给display
加归属void Book::display(){cout<<"书名;"<<bookname<<" 价格:"<<price<<endl;}
4.局外static数据声明赋初值没加数据类型int
还有归属
5.优化程序更贴心
解决方案:
#include<iostream>
#include<cstring>
using namespace std;
class Book
{public:
static int number;
Book(char *a,double b);
void display();
void borrow();
void restore(){number++;cout<<"存书";}
private:
char *bookname;
double price;
};
int Book::number=0;
Book::Book(char *a,double b){
bookname=new char[strlen(a)+1];strcpy(bookname,a);
strcpy(bookname,a);
price=b;
number++;}
void Book::borrow() { number--; cout<<"借出书后图书数量"<<number;}
void Book::display(){cout<<"书名;"<<bookname<<" 价格:"<<price<<endl;}
int main(){
Book a("资治通鉴",78.9);
a.display();
a.borrow();
cout<<endl;
a.restore();
cout<<endl;
cout<<"现有图书数量"<<a.number;}
运行结果