运用C++知识编写程序。首先,创建一个基类 Book,包含书的基本信息,如书名、作者、出版社等。这个类可以包含构造函数、析构函数、复制构造函数等成员函数。为了实现多态输出,可以在这个类中编写一个虚函数 print(),用于输出图书的信息。 然后,可以创建一个派生类 EBook,继承自 Book 类,并增加一些新的成员变量,如电子书的文件格式等。这个类中也可以包含构造函数、析构函数等成员函数。 在主函数中,可以创建一个指向 Book 类的指针数组,然后动态地创建 Book 类的对象和 EBook 类的对象,将这些对象存储到指针数组中。然后,可以通过循环来调用每个对象的 print() 函数,实现多态输出。
时间: 2023-02-13 22:48:21 浏览: 40
这是一个示例代码,希望对你有所帮助:
```
#include <iostream>
#include <string>
using namespace std;
// 定义基类 Book
class Book
{
public:
// 构造函数
Book(string name, string author, string publisher)
: m_name(name), m_author(author), m_publisher(publisher)
{
}
// 析构函数
virtual ~Book()
{
}
// 复制构造函数
Book(const Book &other)
{
m_name = other.m_name;
m_author = other.m_author;
m_publisher = other.m_publisher;
}
// 虚函数,用于输出图书信息
virtual void print()
{
cout << "书名:" << m_name << endl;
cout << "作者:" << m_author << endl;
cout << "出版社:" << m_publisher << endl;
}
private:
string m_name; // 书名
string m_author; // 作者
string m_publisher; // 出版社
};
// 定义派生类 EBook,继承自 Book 类
class EBook : public Book
{
public:
// 构造函数
EBook(string name, string author, string publisher, string format)
: Book(name, author, publisher), m_format(format)
{
}
// 析构函数
virtual ~EBook()
{
}
// 复制构造函数
EBook(const EBook &other)
: Book(other), m_format(other.m_format)
{
}
// 虚函数,用于输出电子书信息
virtual void print()
{
// 调用基类的 print() 函数,输出基本信息
Book::print();
cout << "文件格式:" << m_format << endl;
}
private:
string m_format; // 文件格式
};
int main()
{
Book *ptr[2]; // 定义指向 Book 类的指针数组
// 动态创建 Book 类的对象
ptr
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)