您的位置:首页 > 编程语言 > C语言/C++

C++模板定义与实现分离所导致的链接错误LNK2019

2012-09-25 16:17 483 查看
最近带本科生的数据结构实验课,用C++实现,习惯将模板类的定义与实现分开,分别写在头文件“SeqList.h”和cpp文件“SeqList.cpp”中。然而编译后运行总是出现链接错误,经查资料发现,目前大多数的编译器不支持将模板的定义与实现分开。

有两种方法来解决这个问题。一是将定义与实现都写进头文件里,另一个是在需要使用该模板类的地方添加实现该类的.cpp文件,如“#include "SeqList.cpp"”。简单示例如下所示:

//--------------------------使用VS2012beta--------------------------

//---------------------------Test.h----------------------------

#pragma once

#include "stdafx.h"

using namespace std;

template <class Type>

class Test

{

public:

Test(void);

Test(int x);

~Test(void);

Print();

};

//--------------------------Test.cpp-------------------------------

#include "stdafx.h"

using namespace std;

template <class Type>
Test<Type>::Test(void)
{
}

template <class Type>
Test<Type>::Test(int x)
{
}

template <class Type>
Test<Type>::~Test(void)
{
}

template <class Type>
Test<Type>::Print()
{
}

//--------------------------main.cpp------------------------------
#include "stdafx.h"
#include "Test.cpp"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

Test<int> t;
t.Print();
Test<int> t1(10);
t1.Print();
}

如上所示,红色那行代码便是解决问题的关键。这里要注意在stdafx.h文件中添加#include<iostream>以及#include “Test.h”。注意不要在这个头文件里添加#include “Test.cpp”,而是需要在使用了Test类的地方直接添加。
另外,调用无参构造函数的正确方法是Test<int> t;而不是Test<int> t()!否则会出现warning C4930:main.cpp(25) :
warning C4930: 'Test t(void)': prototyped function not called (was a variable definition intended?)类似的警告,并且t不被编译器认为是Test类实例化后的对象,无法使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: