C++ 友元函数模板 和 友元类模板 和 顺序栈

来源:互联网 发布:香港阿里云服务器 编辑:程序博客网 时间:2024/04/29 22:55

在开始的开始,强烈鄙视清华大学出版社的殷人昆的数据结构,身为一本教材竟然如此多错误!

今天按照那本该死的数据结构写了一个顺序栈,在友元函数模板处遇到无法识别的标识符错误。

friend ostream & operator << (ostream & os,SeqStack<T> & s);

而在类中的友元模板,应该这样用:

1.友元函数模板

template<class T>class A{public:template <class T> friend void fun();}

2.友元类

template<class T>class A{};template<class T>class B{public:    friend class A<T>;}



最后贴上书上的顺序栈SeqStack代码

Stack.h

#pragma onceconst int maxSize = 50;template<class T>class Stack{public:Stack(){};~Stack(){};virtual void Push(const T & x) = 0;virtual bool Pop(T & x) = 0;virtual bool getTop(T & x)const = 0;virtual bool IsEmpty()const = 0;virtual bool IsFull()const = 0;virtual int  getSize()const = 0;};


SeqStack.h

#pragma once#include "Stack.h"#include<assert.h>#include<iostream>using std::ostream;using std::cout;using std::endl;using std::cerr;const int stackIncreament = 20;template<class T>class SeqStack :public Stack<T>{public:SeqStack(int sz=50);~SeqStack();void Push(const T & x);bool Pop(T & x);bool getTop(T & x) const;bool IsEmpty() const;bool IsFull() const;int getSize() const;void MakeEmpty();template <class T> friend ostream & operator << (ostream & cout ,SeqStack<T> & s);private:T * elements;int top;int maxSize;void overflowProcess();};template<class T>SeqStack<T>::SeqStack(int sz = 50) :top(-1), maxSize(sz){elements = new T[maxSize];assert(elements != NULL);}template<class T>SeqStack<T>::~SeqStack(){delete[]elements;}template<class T>void SeqStack<T>::Push(const T & x){if (IsFull() == true)overflowProcess();elements[++top] = x;}template<class T>bool SeqStack<T>::Pop(T & x){if (IsEmpty() == true)return false;x = elements[top--];return true;}template<class T>bool SeqStack<T>::getTop(T & x) const{if (IsEmpty() == true)return false;x = elements[top];return true;}template<class T>bool SeqStack<T>::IsEmpty() const{if (top == -1)return true;elsereturn false;}template<class T>bool SeqStack<T>::IsFull() const{if (top + 1 == maxSize)return true;elsereturn false;}template<class T>int SeqStack<T>::getSize() const{return maxSize;}template<class T>void SeqStack<T>::MakeEmpty(){}template<class T>void SeqStack<T>::overflowProcess(){T * newArray = new T[maxSize + stackIncreament];if (newArray = NULL){cerr << "内存分配失败" << endl;exit(1);}for (int i = 0; i <= top; ++i){newArray[i] = elements[i];}maxSize = maxSize + stackIncreament;delete[]elements;elements = newArray;}template<class T>ostream & operator << (ostream & os, SeqStack<T> & s){int i = s.top;for (; i >= 0; --i){os << "#" << i + 1 << " " << s.elements[i] << endl;}return os;}



原创粉丝点击