题目:
.可以将简单列表描述成下面这样
可存储0或多个某种类型的列表
可创建空列表
可在列表中添加数据项
可确定列表是否为空
可确定列表是否为满
可访问列表中的每一个数据项,并对它执行某种操作
可以看到。这个列表确实简单,列入,他不允许插入或删除数据项。
请设计一个List类来表示这种抽象类型。您应提供头文件list.h和实现文件list.cpp,前者包含类定义,后者包含类方法的实现。您还应创建一个简短的程序来使用这个类。
可以选择使用数组或链表来实现该列表,但公有部分不应该依赖于所做的选择。也就是说,公有接口不应有数组索引,节点指针等。应使用通过概念来表达创建列表在列表中添加数据项等操作。对于访问数据项以及执行操作,通常应使用将函数指针作为参数的函数来处理:
void visit(void (*pf)(Item &));
其中,pf指向一个将Item引用作为参数的函数(不是成员函数),Item是列表中数据项的类型。visit()函数将该函数用于列表中的每个数据项
源代码:
list.h
#ifndef STACK_H_
#define STACK_H_
#include <iostream>
typedef struct List {
char fullname[35];
double payment;
}Item;
class Stack
{
private:
Item items[10];
int line;
public:
Stack();
bool isempty() const;
bool isfull() const;
bool push(char * fullname_tmp,double payment_tmp);
void visit(void (*pf)(Item& x));
};
void print(Item& x);
#endif
list.cpp
#include "test.h"
#include <iostream>
#include <cctype>
int main()
{
using namespace std;
Stack x;
int i=0;
char ch;
char fullname_tmp[35];
double payment_tmp;
cout << "请选择输入(输入为a)还是退出(退出按q): ";
(cin >> ch).get();
while(ch != 'q' && i < 10)
{
cout << "请输入fullname: ";
cin.getline(fullname_tmp, 35);
cout << "请输入payment: ";
(cin >> payment_tmp).get();
x.push(fullname_tmp,payment_tmp);
i++;
cout << "请选择输入(输入为a)还是退出(退出按q): ";
(cin >> ch).get();
}
x.visit(print);
return 0;
}
list_function.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "test.h"
Stack::Stack()
{
line = 0;
}
bool Stack::isempty() const
{
if (line == 0)
return 1;
else
return 0;
}
bool Stack::isfull() const
{
if (line == 10)
return 1;
else
return 0;
}
bool Stack::push(char* fullname_tmp, double payment_tmp)
{
if (isfull())
return 0;
else
{
strcpy(items[line].fullname, fullname_tmp);
items[line].payment = payment_tmp;
line++;
}
}
void Stack::visit(void (*pf)(Item& x))
{
for (int i = 0; i < line; i++)
{
pf(items[i]);
}
}
void print(Item& x)
{
std::cout << x.fullname << " " << x.payment << std::endl;
}
演示效果:
如果朋友你感觉文章的内容对你有帮助,可以点赞,关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈