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 <iostream>
using namespace std;

template<typename T, int size = 0>
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<typename T, int size>
FIFOQueue<T, size>::FIFOQueue()
{
	first = last = -1;
}

template<typename T, int size>
bool FIFOQueue<T, size>::is_empty() const
{
	return (first == -1);
}

template<typename T, int size>
bool FIFOQueue<T, size>::is_full() const
{
	return first == 0 && last == size - 1 || last == first - 1;
}

template<typename T, int size>
void FIFOQueue<T, size>::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<typename T, int size>
T FIFOQueue<T, size>::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<typename T, int size>
void FIFOQueue<T, size>::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<int, 8> duilie;
	for (int i = 0; i < 8; ++i)
	{
		duilie.enqueue(a[i]);
	}
	duilie.traverse();
	duilie.dequeue();//出隊
	duilie.dequeue();//出隊
	duilie.traverse();

	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章