C++ 模板类构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16903788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Template class constructor
提问by xlw12
Ok guys... I have following class
好的,伙计们......我有以下课程
#include <functional>
template <typename TValue, typename TPred = std::less<TValue>>
class BinarySearchTree {
struct TNode {
TValue value;
TNode *pLeft;
TNode *pRight;
};
public:
BinarySearchTree();
~BinarySearchTree();
. . .
private:
TNode *pRoot;
. . .
};
then in my .cpp file i defined the ctor/dtor like this:
然后在我的 .cpp 文件中,我像这样定义了 ctor/dtor:
template <typename TValue, typename TPred>
BinarySearchTree<TValue, TPred>::BinarySearchTree() : pRoot(0) {}
template <typename TValue, typename TPred>
BinarySearchTree<TValue, TPred>::~BinarySearchTree() {
Flush(pRoot);
}
my main function:
我的主要功能:
int main() {
BinarySearchTree<int> obj1;
return 0;
}
and i get following linkage error:
我收到以下链接错误:
public: __thiscall BinarySearchTree<int,struct std::less<int>>::BinarySearchTree<int,struct std::less<int> >(void)
i tried to put the constructor definition into the header file and i get no error. only if i try to define it in the cpp file.
我试图将构造函数定义放入头文件中,但没有出现错误。只有当我尝试在 cpp 文件中定义它时。
回答by Ralph Tandetzky
Don't define templates in the cpp file, but put the implementation of the functions in the header file and leave your main function as it is. Templates get inlined by default. Therefore they are not visible to the linker. And the file that contains main() cannot see the definition of the templates. Hence the error.
不要在cpp文件中定义模板,而是将函数的实现放在头文件中,保持你的主函数原样。模板默认被内联。因此,它们对链接器不可见。并且包含 main() 的文件看不到模板的定义。因此错误。
回答by Dineshkumar
leave space at last and try. it might be taken as shift left operator!
最后留空间试试。它可能被视为左移运算符!
template <typename TValue, typename TPred = std::less<TValue> >