面向对象程序设计示例

1.家庭中体育锻炼类的设计(据说某届DLUT期末考题)

分析:

主要有两个类 成员(Members)和 家庭(Family);

其中的成员类(Members)派生出多个子类:爸爸(Father)、妈妈(Mother)、儿子、隔壁老王、花Q 等等,并且后续可以添加;

成员类(Members)中有一个纯虚函数 运动(sports),在其子类中有不同的实现方法;

家庭类(Family)中包含 成员类型的指针数组和成员个数,运动函数(sports)的实现为遍历其所有成员的运动函数,每添加一个新成员时需要使用add函数传入该对象的指针并加入到指针数组中;

#include
using namespace std;
class Members 
{
public:
	virtual void sports() = 0;
};

class Father :public Members
{
public:	void sports() { cout << "羽毛" << endl; }
};
class Mother :public Members 
{
public:	void sports() { cout << "健美" << endl; }
};

class Family
{
private:
	Members * mem[5];
	int num;
public:
	Family() :num(0) {}
	void	sports() 
	{
		for (int i = 0;i < num;i++)
			mem[i]->sports();
	}
	void add(Members * m) 
	{
		mem[num++] = m;
	}
};
int main() {
	Family f1;
	Father fa1;
	Mother m1;
	f1.add(&fa1);
	f1.add(&m1);
	f1.sports();
	getchar();
}

2.图书管理类(其实就是扒上面的那个)

#include
#include
using namespace std;
class Document
{
public:
	virtual void print() = 0;
};
class Periodical :public Document
{
private:
	int year, peice, period, page, price;
public:
	Periodical(int year = 0, int peice = 0, int period = 0, int page = 0, int price = 0) :year(year), peice(peice), period(period), page(page), price(price) {}
	void print()
	{
		cout << "期刊类:" << endl;
		cout << "年" << year << endl;
		cout << "卷" << peice << endl;
		cout << "期" << period << endl;
		cout << "页码" << page << endl;
		cout << "价格" << price << endl;
		cout << endl;
	}
};
class Book :public Document
{
private:
	string name, author, ISBN;
	int  year, price;
public:
	Book(string name = "no name", string author = "no author", string ISBN = "no ISBN", int year = 0, int price = 0) :name(name), author(author), ISBN(ISBN), year(year), price(price) {}
	void print()
	{
		cout << "书籍类:" << endl;
		cout << "书名" << name << endl;
		cout << "作者" << author << endl;
		cout << "ISBN" << ISBN << endl;
		cout << "出版年" << year << endl;
		cout << "价格" << price << endl;
		cout << endl;
	}
};
class Library
{
private:
	int num;
	Document * doc[3];
public:
	Library() :num(0) {}
	void print()
	{
		for (int i = 0;i < num;i++)
		{
			doc[i]->print();
		}
	}
	void add(Document *d)
	{
		doc[num++] = d;
	}
};
int main()
{
	Library l1;
	Periodical p1;
	Book b1,b2;
	l1.add(&p1);
	l1.add(&b1);
	l1.add(&b2);
	l1.print();
	getchar();
}

 

你可能感兴趣的:(C++)