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

C++__类模板的派生

2015-10-13 19:21 423 查看
基础知识:

类模板的派生

       1) 普通类派生类模板

  2) 类模板也可以派生类模板,这时,派生类模板的参数表中应包含基类模板的参数。 

  3) 模板类与普通类一样也具有多继承,即模板类之间允许有多继承。

  可以从类模板派生出新的类,既可以派生类模板,也可以派生非模板类。派生方法:

⑴ 从类模板派生类模板可以从类模板派生出新的类模板,它的派生格式如下例所示:

template <class T>

class base

{

……

};

 

template <class T>

class derive:public base<T>

{

……

};

与一般的类派生定义相似,只是在指出它的基类时要缀上模板参数,即base<T>。

⑵ 从类模板派生非模板类  可以从类模板派生出非模板类,在派生中,作为非模板类的基类,必须是类模板实例化后的模板类,并且在定义派生类前不需要模板声明语句:template<class>。例如:

template <class T>

class base

{

……

};

 

class derive:public base<int>

{

……

};

在定义derive类时,base已实例化成了int型的模板类。

示例
自定义实现的Stack和继承的Deque

#include <iostream>
using namespace std;

#include <iostream>
#include <exception>
using namespace std;

template<typename T>
class Stack
{
protected:
T* pStack;
int _size;
int _top; //top为0, 意味着空栈.
public:
Stack(int _size) :_top(0)
{
pStack = new T[_size];
}

Stack() :_top(0), _size(20)
{
pStack = new T[_size];
}

void push(const T element)
{
pStack[++_top] = element;
}

T pop()throw (out_of_range)
{
if (0 == _top)
throw out_of_range("Stack is empty");
else
return pStack[_top--];
}

T& top()
{
return pStack[_top];
}
virtual ~Stack()
{
delete[] pStack;
}
};

template<typename T>
class Deque : public Stack<T>{
protected:
int _tail;
public:
Deque() :_tail(0), Stack(){}
Deque(int size) :_tail(0), Stack(size){}
T& getFirst()
{
return Stack::top();
}
T& getLast()
{
return pStack[_tail];
}
};

int main(){

try
{
Stack<int> intStack(20);
intStack.push(7);
intStack.top() += 5;
cout << intStack.top() << endl;
cout << intStack.pop() << endl;
cout << intStack.pop() << endl;
}
catch (exception &e)
{
cout << e.what() << endl;
}

try
{
Deque<int> intDeque(20);
intDeque.push(2);
intDeque.getFirst() += 8;
cout << intDeque.getFirst() << endl;
}
catch (exception &e)
{
cout << e.what() << endl;
}
return 0;
}

运行结果:



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