定义一个Document类,有数据成员name, 从Document类派生出Book类,增加数据成员pageCount。 主函数已经提供如下,请勿修改: int main() { Document a("Document1"); Book b("Book1", 100); a.PrintNameOf(); b.PrintNameOf(); }
时间: 2024-01-07 11:04:20 浏览: 28
可以按照如下方式定义Document类和Book类:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Document {
public:
Document(string name): name(name) {}
void PrintNameOf() const {
cout << "This document is named " << name << endl;
}
private:
string name;
};
class Book : public Document {
public:
Book(string name, int pageCount): Document(name), pageCount(pageCount) {}
void PrintNameOf() const {
cout << "This book is named " << name << " and has " << pageCount << " pages." << endl;
}
private:
int pageCount;
};
```
在主函数中,可以这样使用:
```cpp
int main() {
Document a("Document1");
Book b("Book1", 100);
a.PrintNameOf();
b.PrintNameOf();
return 0;
}
```
输出结果为:
```
This document is named Document1
This book is named Book1 and has 100 pages.
```
阅读全文