我正在尝试编写 STL 的派生类 set<>
并发生链接错误。
头文件Set.h
:
#pragma once
#include <set>
using namespace std;
template <class Ty>
class Set : public set<Ty> {
public:
Set(void);
virtual ~Set(void);
};
辅助源文件Set.cpp
:
#include "Set.h"
template <class Ty>
Set<Ty>::Set(void) {}
template <class Ty>
Set<Ty>::~Set(void) {}
主程序:
#include <iostream>
#include "../myLibrary/Set.h"
#pragma comment(lib, "../x64/Debug/myLibrary.lib")
using namespace std;
int main() {
Set<int> s;
s.insert(1); s.insert(2); s.insert(3);
for(Set<int>::const_iterator it = s.begin(); it!=s.end(); it++)
wcout << *it << endl;
return 0;
}
这提高了
Set.obj : *warning* LNK4221:
和
_Entry_myLibrary_TEST.obj :error LNK2019: "public: virtual __cdecl Set<int>::~Set<int>(void)" (??1?$Set@H@@UEAA@XZ)
最佳答案
您的直接问题是将模板函数放入 Set.cpp 中。 模板函数需要对使用它们的代码可见,因此它们需要位于 .h 文件中而不是单独的 .cpp 文件中。
辅助源文件Set.cpp:
#include "Set.h"
template <class Ty>
Set<Ty>::Set(void) {}
template <class Ty>
Set<Ty>::~Set(void) {}
将函数放在标题中,它们需要在使用它们的地方可见。
我会留给其他人指出为什么从 set 继承可能不是你想要做的,因为这不是你的问题。
关于c++ - 试图继承 STL 集时出现链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11875722/