C++定义并实现图书管理类
时间: 2023-08-12 07:44:09 浏览: 166
好的,下面是一个简单的C++图书管理类的定义和实现。
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Book {
public:
Book(string name, string author, string press, int year, float price) :
m_name(name), m_author(author), m_press(press), m_year(year), m_price(price) {}
string getName() const {
return m_name;
}
void setName(string name) {
m_name = name;
}
string getAuthor() const {
return m_author;
}
void setAuthor(string author) {
m_author = author;
}
string getPress() const {
return m_press;
}
void setPress(string press) {
m_press = press;
}
int getYear() const {
return m_year;
}
void setYear(int year) {
m_year = year;
}
float getPrice() const {
return m_price;
}
void setPrice(float price) {
m_price = price;
}
private:
string m_name;
string m_author;
string m_press;
int m_year;
float m_price;
};
class Library {
public:
void addBook(Book book) {
m_books.push_back(book);
}
void removeBook(string name) {
for (auto iter = m_books.begin(); iter != m_books.end(); iter++) {
if ((*iter).getName() == name) {
m_books.erase(iter);
break;
}
}
}
void listBooks() const {
for (auto book : m_books) {
cout << "书名:" << book.getName() << endl;
cout << "作者:" << book.getAuthor() << endl;
cout << "出版社:" << book.getPress() << endl;
cout << "出版年份:" << book.getYear() << endl;
cout << "价格:" << book.getPrice() << endl;
cout << endl;
}
}
private:
vector<Book> m_books;
};
int main() {
Library library;
Book book1("C++ Primer", "Lippman", "电子工业出版社", 2013, 78.00);
Book book2("Effective Modern C++", "Scott Meyers", "人民邮电出版社", 2015, 68.00);
Book book3("STL源码剖析", "侯捷", "电子工业出版社", 2012, 69.00);
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
library.listBooks();
library.removeBook("STL源码剖析");
library.listBooks();
return 0;
}
```
在这个例子中,我们定义了一个`Book`类,用于表示一本书。我们还定义了一个`Library`类,用于管理图书馆的所有图书。在`Library`类中,我们使用一个`vector<Book>`容器来存储所有的图书,并提供了添加、删除和列出图书的方法。在`main`函数中,我们创建了三本书,并将它们添加到图书馆中。然后,我们列出了所有的图书,并从图书馆中删除了一本书。最后,我们再次列出了所有的图书,以验证删除操作是否成功。
阅读全文