苟晨浩宇哪里人:C++的一道编程问题,请各位大侠指教

来源:百度文库 编辑:高校问答 时间:2024/03/29 09:34:18
声明一个抽象类Med作为基类,其中仅包含一个string 类型数据成员title(名称)和两个纯虚函数print()和id()。然后派生出Book类,CD类和Mag类。在Book类中,包含3个string类型数据成员 author(作者), pub(出版者), isbn(书号)和函数成员print()和id()。在CD类中,包含3个string类型数据成员composer(制作者), make(介质形式), number(编号)和函数成员print()和id()。在Mag类中,包含2个string类型数据成员issn(杂志编号), pub(出版者),两个整型数据成员volume(卷), number(号)和函数成员print()和id()。
派生类的print()和id()函数功能请自行设计。
测试用主函数:
int main()
{
Book book("张三", "C++ 语言程序设计", "清华大学出版社", "0-000-00000-1");
Mag mag("辨析C/C++编程模式", "清华大学出版社", "0000-000X", 020, 01);
CD cd("C++源代码", "清华大学出版社", "ARCHIV", "000001");
book.print();
cout << "\tid: " << book.id() << endl;
mag.print();
cout << "\tid: " << mag.id() << endl;
cd.print();
cout << "\tid: " << cd.id() << endl;
return 0;
}
运行结果:
C++ 语言程序设计 , Author: 张三, Publisher: 清华大学出版社.
id: 0-000-00000-1
辨析C/C++编程模式 , Magzine: Vol. 16, No. 1
id: 0000-000X
C++源代码, CD composer:清华大学计算中心
id: ARCHIV000001

#include <iostream>
#include <string> //使用STL中的string模版类
using namespace std;
//把所有代码拷贝到vc6或者visual studio 2005中编译运行即可
//我已经编译运行成功了

//虚基类
class Med
{
protected:
string title; //名称
public:
virtual void print() const=0; //纯虚函数
virtual string id() const=0; //纯虚函数
};

//子类
class Book:public Med
{
private:
string author;//作者
string pub;//出版社
string isbn;//书号
public:
Book(){} //默认构造函数
Book(const char *pauthor,const char *ptitle,const char *ppub,const char *pisbn )
{
author=pauthor;
title=ptitle;
pub=ppub;
isbn=pisbn;
}
void print() const
{
cout<<title<<", Author:"<<author<<", Publisher:"<<pub<<endl;
}
string id() const
{
return isbn;
}
};
class CD:public Med
{
private:
string composer;//制作者
string make;//介质形式
string number;//编号
public:
CD(){};
CD(const char *ptitle,const char *pcomposer,const char *pmake,const char *pnumber)
{
title=ptitle;
make=pmake;
composer=pcomposer;
number=pnumber;
}
void print() const
{
cout<<title<<", CD composer:"<<composer<<endl;
}
string id() const
{
return make+number;
}
};
class Mag:public Med
{
private:
string issn;//杂志编号
string pub;//出版者
int volume;//卷
int number;//号
public:
Mag(){}
Mag(const char *ptitle,const char *ppub,const char *pissn,const int ivolume,const int inumber)
{
title=ptitle;
pub=ppub;
issn=pissn;
volume=ivolume;
number=inumber;
}
void print() const
{
cout<<title<<", Magazine: Vol."<<volume<<", No."<<number<<endl;
}
string id() const
{
return issn;
}
};
int main()
{
Book book("张三", "C++ 语言程序设计", "清华大学出版社", "0-000-00000-1");
Mag mag("辨析C/C++编程模式", "清华大学出版社", "0000-000X", 020, 01);
CD cd("C++源代码", "清华大学出版社", "ARCHIV", "000001");
book.print();
cout << "\tid: " << book.id() << endl;
mag.print();
cout << "\tid: " << mag.id() << endl;
cd.print();
cout << "\tid: " << cd.id() << endl;
return 0;

}