【问题标题】:C++ Unresolved external symbol with Class templates [duplicate]带有类模板的C ++未解析的外部符号[重复]
【发布时间】:2013-12-18 07:01:05
【问题描述】:

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

#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:

//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。所以我搜索了很多关于未解析的外部符号,但没有找到这个案例。那么我的错误是什么?

【问题讨论】:

  • “所以我搜索了很多关于未解析的外部符号,但没有找到这个案例。”真的吗?一个简单的谷歌搜索“模板未解析的外部符号”给你确切的解决方案。

标签: c++ class templates external


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-08-12
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多