本代码是从其他人的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;
}