C++primer plus第六版课后编程练习答案10.8

头文件
#ifndef LISt_H_
#define LIST_H_

#include<iostream>
using namespace std;

static const int max=10;

template <class T>
class List
{
	T t[max];
	int n;
public:
	List(){n=0;}
	void add(T a);
	bool isFull();
	bool isEmpty();
	void visit(void (*pf)(T &));

};


template<class T>
void show(T &t){cout<<t<<endl;}


template <class T>//每一个代码块都需要一个函数模板
void List<T>::add(T a)
{
	if(isFull())
	{
		cout<<"list is full"<<endl;
	}
	else
	{
		t[n]=a;
		n++;
	}
}

template <class T>
bool List<T>::isEmpty()
{
	if(n<0||n>max)
	{
		cout<<"error!"<<endl;
		n=0;
		return 0;
	}
	else if(0==n)
		return 1;
	else
		return 0;
}

template <class T>
bool List<T>::isFull()
{
	if(n<0||n>max)
	{
		cout<<"error!"<<endl;
		n=0;
		return 0;
	}
	if(max==n)
		return 1;
	else
		return 0;
}

template<class T>
void List<T>::visit(void (*pf)(T &a))
{
	if(isEmpty())
	{
		cout<<"list is empty"<<endl;
	}
	else
	{
		for(int i=0;i<n;i++)
		show(t[i]);
	}
}

#endif
#include<iostream>
#include "list.h"

using namespace std;

void main()
{
	List<double> m;//当构造函数是无参数函数时,list l;
	List<int> n;//有模板的话要在函数后标明函数类型
	double a[5]={1.1,2.2,3.3,4.4,5.5};
	int b[5]={1,2,3,4,5};
	m.visit(show);
	for(int i=0;i<5;i++)
	{
		m.add(a[i]);

	}

	for(i=0;i<5;i++)
		n.add(b[i]);
	for(i=0;i<5;i++)
		n.add(b[i]);
	n.add(8);

	m.visit(show);
	n.visit(show);


}
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值