下面是使用 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