C ++具有类模板的未解析的外部符号 [英] C++ Unresolved external symbol with Class templates

查看:151
本文介绍了C ++具有类模板的未解析的外部符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个在C ++中使用类模板的简单示例。此代码适用。

Here's a simple example of using class templates in C++. This code works.

#include <iostream>

using namespace std;

template <class T>
class Test {
public:
   Test();
   void print();
private:
    int i;
};

template <class T>
Test<T>::Test() {
    i=1;
    cout<<"New instance"<<endl;
}

template <class T>
void Test<T>::print() {
    cout<<"Test"<<endl;
}

int main() {
    Test<int> i;
    i.print();
    return 0;
}

所以当我在3个文件中分离这个代码:main.cpp,Test。 h,Test.cpp:

So when I separate this code in 3 files: main.cpp, Test.h, Test.cpp:

//Test.h
#include <iostream>

using namespace std;

template <class T>
class Test {
public:
   Test();
   void print();
private:
    int i;
};

//Test.cpp
#include "Test.h"

template <class T>
Test<T>::Test() {
    i=1;
    cout<<"New instance"<<endl;
}

template <class T>
void Test<T>::print() {
    cout<<"Test"<<endl;
}

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

using namespace std;

int main() {
    Test<int> i;
    i.print();
    return 0;
}

我收到错误:

1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall Test<int>::print(void)" (?print@?$Test@H@@QAEXXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Test<int>::Test<int>(void)" (??0?$Test@H@@QAE@XZ) referenced in function _mai
1>C:\Programming\C++\stuff\templass\Debug\templass.exe : fatal error LNK1120: 2 unresolved externals

我使用Microsoft Visual C ++ 2010 Express。所以我搜索了很多关于未解决的外部符号,但没有发现这种情况。那么我的错误是什么?

I use Microsoft Visual C++ 2010 Express. So I searched a lot about unresolved external symbol but didn't find anymore for this case. So what's my mistake?

推荐答案

模板不能像任何其他源文件一样进行编译。接口和实现都应该存在于头文件中(尽管有些分开在 .hpp 接口和 .ipp 文件,然后在 .hpp 文件的末尾包含 .ipp 文件。

Templates cannot be compiled like any other source file. Both interface and implementation should live in the header file (although some split them in .hpp files for interface and .ipp files for implementation, and then include the .ipp file at the end of the .hpp file).

编译模板类时,编译器如何知道生成哪些类?

How would the compiler know what classes to generate when the template class is compiled?

这篇关于C ++具有类模板的未解析的外部符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆