用C++语言直接写一个代码不要复述文字在主函数中,可以创建一个指向 Book 类的指针数组,然后动态地创建 Book 类的对象和 EBook 类的对象,将这些对象存储到指针数组中。然后,可以通过循环来调用每个对象的 print() 函数,实现多态输出。
时间: 2023-02-07 15:33:35 浏览: 60
下面是一个实现多态输出的例子:
```
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
Book(string title, string author) : title(title), author(author) {}
virtual void print() { cout << title << " by " << author << endl; }
private:
string title;
string author;
};
class EBook : public Book {
public:
EBook(string title, string author, string format) : Book(title, author), format(format) {}
void print() { cout << title << " by " << author << " (" << format << ")" << endl; }
private:
string format;
};
int main() {
// 创建一个指向 Book 类的指针数组
Book* books[2];
// 动态地创建 Book 类的对象和 EBook 类的对象,并将这些对象存储到指针数组中
books[0] = new Book("The Great Gatsby", "F. Scott Fitzgerald");
books[1] = new EBook("Pride and Prejudice", "Jane Austen", "PDF");
// 通过循环来调用每个对象的 print() 函数,实现多态输出
for (int i = 0; i < 2; i++) {
books[i]->print();
}
return 0;
}
```
编译并运行上面的代码会输出:
```
The Great Gatsby by F. Scott Fitzgerald
Pride and Prejudice by Jane Austen (PDF)
```
注意:在上面的代码中,我们使用了 `virtual` 关键字来修饰 `Book` 类的 `print()` 函数。这个关键字用于告诉编译器在运行时会根据对象的实际类型来调用对应的函数。
希望这个例子能帮到你。