首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

类模板怎么实例化有关问题

2013-12-13 
类模板如何实例化问题本帖最后由 chenxue1111 于 2013-12-06 11:17:45 编辑按数据结构写了一个栈的类模板,

类模板如何实例化问题
本帖最后由 chenxue1111 于 2013-12-06 11:17:45 编辑 按数据结构写了一个栈的类模板,把模板类的实现整个放在了一个头文件里头


#include <iostream>
#include <assert.h>
using namespace std;
const int StackIncreament = 20;
template<typename T>
class SeqStack                                      //: public Stack<T> 
{
private:
T* Elements;
int top;
int MaxSize;
void OverflowProcess();
public:
SeqStack(int sz = 50);
~SeqStack(){delete []Elements;};
void Push(const T&);
bool Pop(T& );
bool GetTop(T&);
int GetSize()const{return  top + 1;}
bool IsEmpty()const {return top == -1?1:0;}
bool IsFull()const {return top == MaxSize -1 ? 1:0}
void MakeEmpty(){top = -1;}
friend ostream& <<(ostream& os, SeqStack<T>&s);
};

template<typename T>
void SeqStack<T>::OverflowProcess()
{
MaxSize = MaxSize + StackIncreament;
T* NewArry = new T[MaxSize];
assert(NewArry != NULL);
for (int i = 0; i != top + 1; i++)
{
NewArry[i] = Elements[i];
}
delete []Elements;
Elements = NewArry;
}

template<typename T>
SeqStack<T>::SeqStack(int sz):MaxSize(sz),top(-1)
{
    Elements = new T[sz];
assert(Elements != NULL);
}

template<typename T>
void SeqStack<T>::Push(const T& x)
{
if (IsFull())
{
OverflowProcess();
}
top++;
Elements[top] = x;

}

template<typename T>
bool SeqStack<T>::Pop(T& x)
{
if (IsEmpty())
{
return false;
}
x = Elements[top];
top--;
return true;
}

template<typename T>
bool SeqStack<T>::GetTop(T& x)
{
if (IsEmpty())
{
return false;
}
x = Elements[top];
return true;
}

template<typename T>
ostream& operator<<(ostream& os,SeqStack<T>& s)
{
os<<"top = "<<s.top<<endl;
for (int i = 0; i != s.top + 1; i++)
{
os<<i<<":"<<s.Elements[i]<<endl;
}
return os;
}

单独编译可以通过
然后希望在main函数里头包含它,还没有实例化仅仅是包含这个头文件,
#include <iostream>
#include"SeqStack.h"
using namespace std;
int main()
{

return 0;
}

就会编译出错。错误为error C2059: syntax error : '<<'
      see reference to class template instantiation 'SeqStack<T>' being compiled
             unexpected token(s) preceding ';'
模板具体应该如何实例化呢
[解决办法]
.h文件第23行,少了一个operator,

实例化像这样
SeqStack<int>  istack;//栈中存储的element为int型
SeqStack<string> sstack;//string型
cout<<istack.IsEmpty();
cout<<sstack.IsFull();

另外 第21行少了个分号
[解决办法]
第23 行 friend ostream& <<(ostream& os, SeqStack<T>&s); 
少了 operator,而且<T> 不是必须的。

改为
friend ostream& operator<<(ostream& os, SeqStack& s);

其实 这个函数应该是这样的。
friend ostream& operator<<(ostream& os, const SeqStack& s);

热点排行