Edu*_*uca 0 c++ linker visual-c++
因此,我创建了一个基本的 VC++ 程序,并创建了一个具有 1 个方法的模板类(除了构造函数和析构函数)。我收到以下错误:
>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Vector<int>::~Vector<int>(void)" (??1?$Vector@H@@QAE@XZ) referenced in function _main
>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Vector<int>::Vector<int>(int)" (??0?$Vector@H@@QAE@H@Z) referenced in function _main
>c:\users\edy\documents\visual studio 2010\Projects\ex01\Debug\ex01.exe : fatal error LNK1120: 2 unresolved externals
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
(CPP 类文件)
using namespace std;
#include "Vector.h"
template <class T> Vector<T>::Vector(int n)
{
this.crt = 0;
this.dim = n;
this.elem = new T[100];
}
template <class T> void Vector<T>::add(T e)
{
this.elem[crt] = e;
this.crt++;
}
template <class T> Vector<T>::~Vector(void)
{
this.crt = 0;
}
Run Code Online (Sandbox Code Playgroud)
(H类文件)
#pragma once
template <class T> class Vector
{
public:
int dim;
T* elem;
Vector(int n);
void add(T e);
~Vector(void);
private:
int crt;
};
Run Code Online (Sandbox Code Playgroud)
(主文件)
using namespace std;
#include "Vector.h"
int main(void)
{
Vector<int> x(5);
//x.add(1); <--- if i decomment this line, it throws an additional error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
大多数解决方案都涉及未实现的方法,但我已经实现了所有方法。我不知道有什么问题。有什么帮助吗?
模板类实现需要对使用它们的所有翻译单元可见。将实现移动到头文件中。
在您询问之前 - 不,没有办法隐藏它们,除非您事先知道您拥有该课程的哪些专业。如果你希望你Vector是通用的,实现需要是可见的。
如果您想将它们分开,通常的做法是将实现放在.impl包含在标题中的文件中。