模板类使用时,经常会遇到的问题解析

 最近按照书本写了下模板类,熟悉下其使用方法。按照以往的编程风格,我们会把类的声明写在头文件中,而把类的实现部分写在cpp头文件中。

然而对于模板类,这种做法最容易遇到一个奇怪的问题,具体描述如下:

编程环境:VC6.0

语言: c++

 

情况一:把模板类的声明和定义都写在头文件中时,编译通过,且正常运行。

情况二:当声明和定义分开写时,main.cpp 里头引入模板类的头文件则编译通过,当build时有错误。

情况三:当声明和定义分开写时,main.cpp 里头引入模板类的cpp文件则编译通过,build时也正常,可以正常运行。

 

stack.h 文件:

#ifndef STACK_H
#define STACK_H

#define DEFAULT_SIXE  20

template <class Elem>
class Stack
{
private:
	int top;
	Elem* listArray;
	int maxSize;

public:
	Stack(int size = DEFAULT_SIXE)
	{
		maxSize = size;
		listArray = new Elem[maxSize];
		top = 0;
	}
	~Stack(){ delete[] listArray; }	
	void clear();
	bool push(const Elem& data);
	bool pop(Elem& data);
	bool topValue(Elem& data) const;
	int length() const { return top; }
};




#endif


stack.cpp文件:

#include "stack.h"

template <class Elem>
void Stack<Elem>::clear()
{
	top = 0;
}

template <class Elem>
bool Stack<Elem>::push(const Elem& data)
{
	if (top == maxSize)
	{
		return false;
	}
	listArray[top++] = data;
	return true;
}

template <class Elem>
bool Stack<Elem>::pop(Elem& data)
{
	if (top == 0)
	{
		return false;
	}
	data = listArray[--top];
	return true;
}

template <class Elem>
bool Stack<Elem>::topValue(Elem& data) const
{
	if (top == 0)
	{
		return false;
	}
	data = listArray[top-1];
	return true;
}


main.cpp文件:

#include "stack.h"
#include <iostream.h>

int main()
{
	Stack<int> s(3);
	s.push(23);
	s.push(34);
	s.push(2);

	int r;
	s.pop(r);
	cout<<r<<endl;
	
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值