请结合你的生活,举一个身边的例子(实体或非实体,请不要使用“时钟”的案例),用自己的方法对该实体进行抽象,简述自己对物体“属性”和“行为”进行抽象的思考过程,并提供完整的类的封装形,用c++来写
时间: 2024-12-16 10:19:46 AIGC 浏览: 47
在生活中,我们可以拿一本书作为例子来说明。书籍是一种实体,它具有特定的属性,如书名、作者、出版社、页数等,这些都是它的静态特性。同时,书籍也有一定的行为,比如我们能阅读它获取信息,可以将其借给别人,甚至可以将其归还到图书馆。
在抽象这个过程中,我会首先提取出书籍的核心特征,即名称(Title)、作者(Author)、出版信息(Publisher)和页码(Pages)。然后将这些作为类的数据成员(属性)。对于行为,我可以抽象为读取内容(Read)、借阅(Lend)、归还(Return)等操作。
```cpp
class Book {
private:
std::string title; // 书籍标题 - 属性
std::string author; // 作者姓名 - 属性
std::string publisher; // 出版社 - 属性
int pages; // 页数 - 属性
public:
// 构造函数
Book(const std::string& title, const std::string& author, const std::string& publisher, int pages)
: title(title), author(author), publisher(publisher), pages(pages) {}
// 行为抽象
void read() { /* 模拟读取内容 */ }
void lend(std::string borrower) { /* 模拟借书给borrower */ }
void returnBook() { /* 模拟归还书籍 */ }
// 可视化表示
virtual std::string displayInfo() {
return "Title: " + title + ", Author: " + author + ", Publisher: " + publisher + ", Pages: " + std::to_string(pages);
}
};
```
在这个例子中,`displayInfo()`是一个虚函数,实现了多态性。当需要显示书籍信息时,无论具体的书是什么类型(例如小说、教科书等),都可以通过这个公共接口获取信息。
阅读全文
相关推荐



















