定义一个Document类,有数据成员name, 从Document类派生出Book类,增加数据成员pageCount。 主函数已经提供如下,请勿修改: int main() { Document a("Document1"); Book b("Book1", 100); a.PrintNameOf(); b.PrintNameOf(); }
时间: 2024-01-07 07:04:43 浏览: 42
下面是定义Document类和Book类的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Document {
public:
Document(string name) : name(name) {}
void PrintNameOf() {
cout << "Name of the document: " << name << endl;
}
private:
string name;
};
class Book : public Document {
public:
Book(string name, int pageCount) : Document(name), pageCount(pageCount) {}
void PrintNameOf() {
cout << "Name of the book: " << Document::name << endl;
}
private:
int pageCount;
};
int main() {
Document a("Document1");
Book b("Book1", 100);
a.PrintNameOf();
b.PrintNameOf();
return 0;
}
```
在上面的代码中,我们定义了Document类和Book类。Document类有一个数据成员name,表示文档的名称;Book类是从Document类派生出来的,增加了一个数据成员pageCount,表示书的页数。
在主函数中,我们分别创建了一个Document对象a和一个Book对象b,并调用它们的PrintNameOf()函数来输出它们的名称。注意,我们在Book类中重载了PrintNameOf()函数,因为Book类需要输出的是“Name of the book”而不是“Name of the document”。在PrintNameOf()函数的实现中,我们调用了基类的name成员,以获取Document对象的名称。