用C++语言直接写一个代码不要复述文字,要求 在主函数中,可以创建一个指向 Book 类的指针数组,然后动态地创建 Book 类的对象和 EBook 类的对象,将这些对象存储到指针数组中。然后,可以通过循环来调用每个对象的 print() 函数,实现多态输出。 另外,可以编写一个静态函数 menu(),用于输出操作菜单,让用户选择要进行的操作,例如添加图书、删除图书等。
时间: 2023-02-16 12:21:13 浏览: 49
下面是使用 C 语言实现的代码,请注意,因为这段代码未经过编译和测试,可能存在语法错误:
```
#include <stdio.h>
#include <stdlib.h>
// 定义 Book 类
class Book {
public:
Book(char* title, char* author, int pages) {
this->title = title;
this->author = author;
this->pages = pages;
}
virtual void print() {
printf("Book: %s, Author: %s, Pages: %d\n", title, author, pages);
}
private:
char* title;
char* author;
int pages;
};
// 定义 EBook 类
class EBook {
public:
EBook(char* title, char* author, int pages, char* format) {
this->title = title;
this->author = author;
this->pages = pages;
this->format = format;
}
virtual void print() {
printf("EBook: %s, Author: %s, Pages: %d, Format: %s\n", title, author, pages, format);
}
private:
char* title;
char* author;
int pages;
char* format;
};
// 定义菜单函数
static void menu() {
printf("1. Add book\n");
printf("2. Remove book\n");
printf("3. Print books\n");
printf("4. Quit\n");
}
int main() {
// 创建指向 Book 类的指针数组
Book** books = (Book**) malloc(sizeof(Book*) * 100);
while (1) {
menu(); // 输出菜单
int choice;
scanf("%d", &choice); // 读入用户的选择
if (choice == 1) {
// 添加图书
int type;
printf("Enter 1 for book, 2 for eBook: ");
scanf("%d", &type);
if (type == 1) {
// 动态地创建 Book 类的对象
char title[100], author[100];
int pages;
printf("Enter title, author, pages: ");
scanf("%s%s%d", title, author, &pages);
Book* book = new Book(title, author, pages);
// 将对象存储到指针数组中
static int count = 0;
books[count++] = book;
} else
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)