分页: 1 / 1

关于C++中template的问题

发表于 : 2007-08-08 2:31
liuhello

代码: 全选

/*不用temlate的时候我把声明放在Test.h的文件里再把定义放在Test.cpp的文件里没有错误出现
 * 而现在我想用temlate来实现摸板,同样把函数display的声明放在Test.h下,而把具体实现放
 * 在了Test.spp下却出现了“undefined reference to `Test<int>::display()'”的问题
 * 这是怎么一回事啊。是我那里出现了问题吗?
 * 具体代码如下:
 */
//************************************************************************
//***************"Test.h"**************************************************
#ifndef TEST_H_
#define TEST_H_
#include <iostream>
template <typename T>
class Test
{
public:
	Test(){};
	Test(T _data,Test* _next = 0):data(_data),next(_next){}
	virtual ~Test(){};
	void display();
private:
	T data;
	Test *next;
};

#endif /*TEST_H_*/
//*****************************************************************************
//Test.cpp
#include "Test.h"

template<typename T>
void Test<T>::display()
{
	std::cout<<this->data<<"  ";
	Test *tmp = this->next;
	while(tmp != 0)
	{
		std::cout<<tmp->data<<"  ";
		tmp = tmp->next;
	}
}
//*****************************************************************************
//main.cpp
#include "Test.h"

int main()
{
	Test<int> hello(2,new Test<int>(3,new Test<int>(4)));
	hello.display();                      //这里报错:undefined reference to `Test<int>::display()'
	return 0;
	
}
这只是个测试的类 谁能具体帮我解释下吗?
谢谢!!!!!!!!

发表于 : 2007-08-08 13:50
madoldman
不要把模板类的声明和实现放在两个文件里,模板编译中不产生实际代码,只有加模板参数使用时才产生代码,因此如果分两个文件,连接时会出错。

发表于 : 2007-08-08 15:57
liuhello

谢谢拉