您的位置:首页 > 编程语言 > C语言/C++

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

2015-11-30 16:13 585 查看
头文件
#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
=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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: