C++Primer Plus(第六版) 第十章 第八题

本文介绍了一个自定义的C++列表类的实现过程,包括结构定义、成员函数及其实现细节,并通过一个电影信息录入与展示的例子展示了如何使用该列表类。此列表类支持添加元素、检查空满状态、遍历列表等功能。

本代码是从其他人的pdf答案中粘贴过来的,我不知道出处在哪,如有侵犯权益或知道出处的,请联系我。

本题难点在visit函数,它其实是函数的指针

整个的声明:

#ifndef LIST_H_
#define LIST_H_
const int TSIZE = 50;
struct film
{
	char title[TSIZE];
	int rating;
};
typedef struct film Item;
const int LISTMAX = 10;
class List
{
public:
	List();
	~List();
	bool isEmpty();
	bool isFull();
	bool addItem(Item item);
	int itemCount();
	void visit(void(*pf)(Item &));

private:
	Item items[LISTMAX];
	int count;
};

#endif // !LIST_H_


定义:

#include "list.h"

List::List()
{
	count = 0;
}

List::~List()
{
}

bool List::isEmpty()
{
	return 0 == count;
}

bool List::isFull()
{
	return LISTMAX == count;
}

bool List::addItem(Item item)
{
	if (LISTMAX == count)
		return false;
	else
	{
		items[count++] = item;
		return true;
	}
}

int List::itemCount()
{
	return count;
}

void List::visit(void(*pf)(Item &))
{
	for (int i = 0; i < count; i++)
	{
		(*pf)(items[i]);
	}
}


使用示例:

#include <iostream>
#include <cstdlib>
#include "list.h"
void showfilm(Item & item);
int main()
{
	using namespace std;
	List movies;
	Item temp;
	if (movies.isFull())
	{
		cout << "No more room in list! Bye!\n";
		exit(1);
	}
	cout << "Enter first movie title:\n";
	while (cin.getline(temp.title, TSIZE) && temp.title[0] != '\0')
	{
		cout << "Enter your rating <1-10>: ";
		cin >> temp.rating;
		while (cin.get() != '\n')
			continue;
		if (movies.addItem(temp) == false)
		{
			cout << "List already is full!\n";
			break;
		}
		if (movies.isFull())
		{
			cout << "You have filled the list.\n";
			break;
		}
		cout << "Enter next movie title (empty line to stop):\n";
	}
	if (movies.isEmpty())
		cout << "No data entered.";
	else
	{
		cout << "Here is the movie list:\n";
		movies.visit(showfilm);
	}
	cout << "Bye!\n";
	cin.get();
	return 0;
}
void showfilm(Item & item)
{
	std::cout << "Movie: " << item.title << " Rating: "
		<< item.rating << std::endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值