用c++语言编写一个完整代码 要求在主函数中,可以创建一个指向 Book 类的指针数组,然后动态地创建 Book 类的对象和 EBook 类的对象,将这些对象存储到指针数组中。然后,可以通过循环来调用每个对象的 print() 函数,实现多态输出。编程不要中断
时间: 2023-02-09 16:35:36 浏览: 127
以下是在 C 语言中使用多态的一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义基类 Book
typedef struct Book {
char* title;
char* author;
int pageCount;
void (*print)(struct Book*); // 函数指针,指向输出函数
} Book;
// 定义派生类 EBook
typedef struct EBook {
Book book;
char* fileSize;
} EBook;
// 定义基类的输出函数
void book_print(Book* book) {
printf("Title: %s\n", book->title);
printf("Author: %s\n", book->author);
printf("Page count: %d\n", book->pageCount);
}
// 定义派生类的输出函数
void ebook_print(Book* book) {
EBook* ebook = (EBook*)book; // 将指向基类的指针转换为指向派生类的指针
printf("Title: %s\n", ebook->book.title);
printf("Author: %s\n", ebook->book.author);
printf("Page count: %d\n", ebook->book.pageCount);
printf("File size: %s\n", ebook->fileSize);
}
int main() {
// 创建指向 Book 类的指针数组
Book** books = (Book**)malloc(sizeof(Book*) * 2);
// 动态创建 Book 类的对象
Book* book1 = (Book*)malloc(sizeof(Book));
book1->title = "Book 1";
book1->author = "Author 1";
book1->pageCount = 100;
book1->print = book_print; // 设置函数指针
books[0] = book1;
// 动态创建 EBook 类的对象
EBook* ebook1 = (EBook*)malloc(sizeof(EBook));
ebook1->book.title = "EBook 1";
ebook1->book.author = "Author 1";
ebook1->book.pageCount = 50;
ebook1->book.print = ebook_print; // 设置函数指针
ebook1->fileSize = "1MB";
books[1] = (Book*)ebook1;
// 通过循环调用每
阅读全文