C++模板编写注意事项!!!dynamic initializer...

以往编程都喜欢.h头文件和.cpp实现文件分开来,今天在拷贝(哈哈)一个FIFO的泛型队列实现时,也这么搞了,结果,悲剧了无论怎么都编译不过,把main函数放到模板类的.cpp实现又可以找得到。

黔驴技穷时,发现真的是自己的无知哦,这好像就是模板的基本规定(不能够分离)啊!!!

http://bbs.csdn.net/topics/391493308?page=1

http://blog.sina.com.cn/s/blog_46625a5f010000ld.html

摘录别人的:

#pragma once

#include 
using namespace std;

template
class FIFOQueue{
public:
	FIFOQueue();
public:
	bool is_empty() const;//是否队空
	bool is_full() const;//是否队满

	void enqueue(const T&);//入队
	T dequeue();//出队

	void traverse() const;//遍历队列(打印)
private:
	T data[size];//数组实现FIFO队列
	int first;
	int last;
};

template
FIFOQueue::FIFOQueue()
{
	first = last = -1;
}

template
bool FIFOQueue::is_empty() const
{
	return (first == -1);
}

template
bool FIFOQueue::is_full() const
{
	return first == 0 && last == size - 1 || last == first - 1;
}

template
void FIFOQueue::enqueue(const T& elem)
{
	if (!is_full())
	{
		if (last == -1 || last == size - 1)
		{
			data[0] = elem;
			last = 0;
			if (first == -1)
			{
				first = 0;
			}
		}
		else
		{
			data[++last] = elem;
		}
	}
	else
	{
		cout << "FIFOQueue full." << endl;
	}
}

template
T FIFOQueue::dequeue()
{
	if (is_empty())
	{
		cout << "FIFOQueue empty." << endl;
	}

	T tmp;
	tmp = data[first];
	if (first == last)
	{
		last = first = -1;
	}
	else if (first == size - 1)
	{
		first = 0;
	}
	else
	{
		++first;
	}

	return tmp;
}

template
void FIFOQueue::traverse() const
{
	for (int i = first; i <= last; ++i)
	{
		cout << data[i] << " ";
	}
	cout << endl;
}

使用:
int main(int argc, char * argv[])
{
	int a[8] = { 50, 10, 20, 30, 70, 40, 80, 60 };
	Queue duilie;
	for (int i = 0; i < 8; ++i)
	{
		duilie.enqueue(a[i]);
	}
	duilie.traverse();
	duilie.dequeue();//出队
	duilie.dequeue();//出队
	duilie.traverse();

	return 0;
}


你可能感兴趣的:(编程经验)