定义一个Document类,有数据成员stringname、函数printname();从Document类派生出Book类,增加数据成员int pageCount;函数printBook()。要求调用printBook()可以打印name、pageCount. 声明BookDemo,打印Book信息。
时间: 2024-02-24 17:58:30 浏览: 65
以下是定义Document类和从Document类派生出Book类的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Document {
protected:
string name;
public:
Document(string n) : name(n) {}
void printname() {
cout << "Document name: " << name << endl;
}
};
class Book : public Document {
private:
int pageCount;
public:
Book(string n, int p) : Document(n), pageCount(p) {}
void printBook() {
cout << "Book name: " << name << endl;
cout << "Page count: " << pageCount << endl;
}
};
```
然后,可以创建一个BookDemo类实例,调用printBook函数输出Book的信息:
```cpp
int main() {
BookDemo bookdemo("The Great Gatsby", 180);
bookdemo.printBook();
return 0;
}
```
输出结果为:
```
Book name: The Great Gatsby
Page count: 180
```
阅读全文