首页 > 试题广场 >

定义一个 Document 类,有 name 成员变量,从

[问答题]

定义一个 Document 类,有 name 成员变量,从 Document 派生出 Book 类,增加 PageCount变量。

推荐

解:

#include <iostream.h>
#include <string.h>
class Document
{
public:
Document(){};
Document( char *name );
char *Name; // Document name.
void PrintNameOf(); // Print name.
};
Document::Document( char *name )
{
Name = new char[ strlen( name ) + 1 ];
strcpy( Name, name );
};
void Document::PrintNameOf()
{
cout << Name << endl;
}
class Book : public Document
{
public:
Book( char *name, long pagecount );
void PrintNameOf();
private:
long PageCount;
};
Book::Book( char *name, long pagecount ):Document(name)
{
PageCount = pagecount;
}
void Book::PrintNameOf()
{
cout << "Name of book: ";
Document::PrintNameOf();
}
void main()
{
Document a("Document1");
Book b("Book1",100);
b.PrintNameOf();
}

程序运行输出:

Name of book: Book1



发表于 2018-04-18 20:47:28 回复(0)