目录
一、实验内容
1.模板函数(compare)
一般模板函数
特化模板函数
2、模板类Queue或Stack
模板类(Queue,Stack)
成员模板函数
模板特化:模板函数特化、模板成员函数特化、模板类特化
3、模板类AutoPtr
构造函数
析构函数
拷贝构造函数
等号、->、*等运算符重载
主函数调用AutoPtr
二、代码实现
1.queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include <cstdlib>
using namespace std;
//类模板:用于生成类
template<class Type> class queue;
template<class Type> class queueItem;
template<class Type> class queueItem
{
Type item;
queueItem* next;
queueItem(const Type& t) :item(0), next(0) {
}
friend class queue<Type>; //友元类,目的访问这里面的私有成员
friend ostream& operator<<(ostream& os, const queue<Type>& q);
public:
queueItem<Type>* operator++() {
//重载运算符++ 用于指向队列里的下一个元素(指针类型)
return next;
}
Type& operator*() {
//重载运算符* 用于取队列里对应指针的值(取地址后 是Type类的)
return item;
}
};
template<class Type> class queue
{
public:
queue() :head(0), tail(0) {
} //初始化
queue(const queue& q) :head(0), tail(0) {
copy_items(q);
}
//函数模板:用于生成函数
template<class It> queue(It beg, It end) : head(0), tail(0) {
//构造函数:拷贝指定起始位置内容的队列
copy_items(beg, end);
}
template<class It> void assign(It beg, It end);
queue& operator=(const queue&);
void push(const Type&); //https://www.cnblogs.com/wss-is-knight/p/3624164.html
void pop();
bool empty() const {
return head == 0;
}
~queue() {
//析构函数
destory();
}
Type& front() {
//取队列头指针的值(取地址符)
return head->item;
}
const Type& front() const {
//返回值不能修改,并且不能修改对应对象中成员函数的值~
return head->item;
}
friend ostream& operator<<(ostream& os, const queue<Type>& q) {
//https://blog.csdn.net/qq_36864672/article/details/76422722
os << "<";
queueItem<Type>* p;