用C++写 定义一个图书类(Book),该类的数据成员有:书名(bookname)、作者(authors)、页数(pages)、出版社(publishing_house)、价格(price),要求如下 : (1)图书的所有属性都是私有的,数据成员的类型根据实际情况来确定; (2)给该类添加相应的getXxx、setXxx函数(例如:char * getBookname()、void setBookname(char * bk))来获取、设置该类的私有成员; (3)给该类添加适当的构造函数、析构函数来初始化、清理对象; (4)在main()函数定义两本图书: 《C++程序设计》,谭浩强编著,485页,清华大学出版社,36.00元 《吹牛大王历险记》,拉斯伯等编著,149页,天津人民出版社,12.80元 然后将这两个对象的成员信息输出到屏幕上。
时间: 2024-01-22 13:18:44 浏览: 93
用c++定义一个Book(图书)类
5星 · 资源好评率100%
下面是实现上述要求的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class Book {
private:
char *bookname;
char *authors;
int pages;
char *publishing_house;
float price;
public:
Book(char *bk, char *at, int pg, char *ph, float pr) {
bookname = new char[strlen(bk) + 1];
strcpy(bookname, bk);
authors = new char[strlen(at) + 1];
strcpy(authors, at);
pages = pg;
publishing_house = new char[strlen(ph) + 1];
strcpy(publishing_house, ph);
price = pr;
}
~Book() {
delete[] bookname;
delete[] authors;
delete[] publishing_house;
}
char* getBookname() {
return bookname;
}
void setBookname(char *bk) {
delete[] bookname;
bookname = new char[strlen(bk) + 1];
strcpy(bookname, bk);
}
char* getAuthors() {
return authors;
}
void setAuthors(char *at) {
delete[] authors;
authors = new char[strlen(at) + 1];
strcpy(authors, at);
}
int getPages() {
return pages;
}
void setPages(int pg) {
pages = pg;
}
char* getPublishing_house() {
return publishing_house;
}
void setPublishing_house(char *ph) {
delete[] publishing_house;
publishing_house = new char[strlen(ph) + 1];
strcpy(publishing_house, ph);
}
float getPrice() {
return price;
}
void setPrice(float pr) {
price = pr;
}
};
int main() {
Book book1("C++程序设计", "谭浩强", 485, "清华大学出版社", 36.00);
Book book2("吹牛大王历险记", "拉斯伯等", 149, "天津人民出版社", 12.80);
cout << "书名:" << book1.getBookname() << endl;
cout << "作者:" << book1.getAuthors() << endl;
cout << "页数:" << book1.getPages() << endl;
cout << "出版社:" << book1.getPublishing_house() << endl;
cout << "价格:" << book1.getPrice() << endl;
cout << endl;
cout << "书名:" << book2.getBookname() << endl;
cout << "作者:" << book2.getAuthors() << endl;
cout << "页数:" << book2.getPages() << endl;
cout << "出版社:" << book2.getPublishing_house() << endl;
cout << "价格:" << book2.getPrice() << endl;
return 0;
}
```
输出结果:
```
书名:C++程序设计
作者:谭浩强
页数:485
出版社:清华大学出版社
价格:36
书名:吹牛大王历险记
作者:拉斯伯等
页数:149
出版社:天津人民出版社
价格:12.8
```
阅读全文