用c++语言编程一个完整代码首先,创建一个基类 Book,包含书的基本信息,如书名、作者、出版社等。这个类可以包含构造函数、析构函数、复制构造函数等成员函数。为了实现多态输出,可以在这个类中编写一个虚函数 print(),用于输出图书的信息。 然后,可以创建一个派生类 EBook,继承自 Book 类,并增加一些新的成员变量,如电子书的文件格式等。这个类中也可以包含构造函数、析构函数等成员函数。 在主函数中,可以创建一个指向 Book 类的指针数组,然后动态地创建 Book 类的对象和 EBook 类的对象,将这些对象存储到指针数组中。然后,可以通过循环来调用每个对象的 print() 函数,实现多态输出。
时间: 2023-02-13 09:12:58 浏览: 53
以下是一个示例代码:
```
#include <iostream>
#include <string>
using namespace std;
// 基类 Book
class Book {
private:
string name;
string author;
string publisher;
public:
// 构造函数
Book(string name, string author, string publisher) {
this->name = name;
this->author = author;
this->publisher = publisher;
}
// 复制构造函数
Book(const Book &book) {
this->name = book.name;
this->author = book.author;
this->publisher = book.publisher;
}
// 析构函数
~Book() {
cout << "Delete book: " << this->name << endl;
}
// 虚函数,用于输出图书的信息
virtual void print() {
cout << "Book: " << this->name << " by " << this->author << endl;
cout << "Publisher: " << this->publisher << endl;
}
};
// 派生类 EBook,继承自 Book 类
class EBook: public Book {
private:
string format;
public:
// 构造函数
EBook(string name, string author, string publisher, string format):
Book(name, author, publisher) {
this->format = format;
}
// 复制构造函数
EBook(const EBook &ebook):
Book(ebook) {
this->format = ebook.format;
}
// 析构函数
~EBook() {
cout << "Delete ebook: " << this->name << endl;
}
// 覆盖虚函数,用于输出电子书的信息
void print() {
cout << "EBook: " << this->name << " by " << this->author << endl;
cout << "Publisher: " << this->publisher << endl;
cout << "Format: " << this->format << endl;
}
};
int main() {
Book *books[2];
books[0] = new Book("C++ Primer Plus", "Stephen Prata", "Addison-Wesley Professional");
books[1] = new EBook("Python Crash Course", "Eric Matthes", "No Starch Press", "PDF");
for (int i = 0; i < 2; i++) {
books[i]->print();
}
delete books[0];
delete books[1];
return 0;
}
```