网站用微信登录 要怎么做,搭建网站平台,wordpress如和安装,如何做网站百科1、类模板 2、使用类模板
类模板在使用的时候要显示的调用是哪种类型#xff0c;而不是像函数模板一样能够根据参数来推导出是哪种类型。 Stack.h
#include stdexcepttemplate typename T
class Stack
{
public:explicit Stack(int maxSize);~Stack();void …1、类模板 2、使用类模板
类模板在使用的时候要显示的调用是哪种类型而不是像函数模板一样能够根据参数来推导出是哪种类型。 Stack.h
#include stdexcepttemplate typename T
class Stack
{
public:explicit Stack(int maxSize);~Stack();void Push(const T elem);void Pop();T Top();const T Top() const;bool Empty() const;private:T* elems_;int maxSize_;int top_;
};template typename T
StackT::Stack(int maxSize) : maxSize_(maxSize), top_(-1)
{elems_ new T[maxSize_];
}template typename T
StackT::~Stack() {delete []elems_;
}template typename T
void StackT::Push(const T elem)
{if (top_ 1 maxSize_){throw std::out_of_range(StackT::Push stack full);}elems_[top_] elem;
}template typename T
void StackT::Pop()
{if (top_ 1 0){throw std::out_of_range(StackT::Pop stack empty);}--top_;
}template typename T
T StackT::Top()
{if (top_ 1 0){throw std::out_of_range(StackT::Top stack empty);}return elems_[top_];
}template typename T
const T StackT::Top() const
{if (top_ 1 0){throw std::out_of_range(StackT::Top stack empty);}return elems_[top_];
}template typename T
bool StackT::Empty() const {return top_ 1 0;
}
main.cpp
#include iostream
using namespace std;
#include Stack.h
int main() {Stackint s(10);s.Push(1);s.Push(2);s.Push(3);while (!s.Empty()){cout s.Top() endl;s.Pop();}return 0;
}// 输出
3
2
1
3、非类型模板参数 Stack2.h
#include stdexcepttemplate typename T, int MAX_SIZE
class Stack2
{
public:Stack2();~Stack2();void Push(const T elem);void Pop();T Top();const T Top() const;bool Empty() const;private:T* elems_;int top_;
};template typename T, int MAX_SIZE
Stack2T, MAX_SIZE::Stack2() : top_(-1)
{elems_ new T[MAX_SIZE];
}template typename T, int MAX_SIZE
Stack2T, MAX_SIZE::~Stack2() {delete []elems_;
}template typename T, int MAX_SIZE
void Stack2T, MAX_SIZE::Push(const T elem)
{if (top_ 1 MAX_SIZE){throw std::out_of_range(Stack2T::Push stack full);}elems_[top_] elem;
}template typename T, int MAX_SIZE
void Stack2T, MAX_SIZE::Pop()
{if (top_ 1 0){throw std::out_of_range(Stack2T::Pop stack empty);}--top_;
}template typename T, int MAX_SIZE
T Stack2T, MAX_SIZE::Top()
{if (top_ 1 0){throw std::out_of_range(Stack2T::Top stack empty);}return elems_[top_];
}template typename T, int MAX_SIZE
const T Stack2T, MAX_SIZE::Top() const
{if (top_ 1 0){throw std::out_of_range(Stack2T::Top stack empty);}return elems_[top_];
}template typename T, int MAX_SIZE
bool Stack2T, MAX_SIZE::Empty() const {return top_ 1 0;
}
main.cpp
#include iostream
using namespace std;
#include Stack2.h
int main() {Stack2int, 10 s;s.Push(1);s.Push(2);s.Push(3);while (!s.Empty()){cout s.Top() endl;s.Pop();}return 0;
}// 输出
3
2
1