问题:
解答:
main.cpp
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
Item item = 0;
List list;
cout << "请输入item(0结束):";
cin >> item;
while (item!=0)
{
cin.get();
list.add(item);
cout << "请输入item(0结束):";
cin >> item;
}
list.visit(visit_Item);
return 0;
}
List.h
#pragma once
typedef unsigned long Item;
void visit_Item(Item&);
class List
{
private:
enum{MAX=10};
Item m_items[MAX];
int m_top;
public:
List();
~List();
bool isempty()const;
bool isfull()const;
bool add(const Item& item);
void visit(void (*p)(Item&));
};
List.cpp
#include "List.h"
#include <iostream>
using namespace std;
List::List()
{
this->m_top = 0;
}
List::~List()
{
}
bool List::isempty()const
{
return this->m_top == 0;
}
bool List::isfull()const
{
return this->m_top == MAX;
}
bool List::add(const Item& item)
{
if (isfull())
{
cout << "列表已满,无法添加!" << endl;
return false;
}
this->m_items[this->m_top++] = item;
return true;
}
void List::visit(void (*p)(Item&))
{
for (int i = 0; i < this->m_top; i++)
{
p(this->m_items[i]);
}
}
void visit_Item(Item&item)
{
cout << "item: " << item << endl;
}
运行结果:
考查点:
- 数据结构顺序表
- 函数指针
2024年9月4日16:53:49