問題描述
我在調用我擁有的模板類時遇到問題.我聲明了一個新的類型名Array,它是一個模板;
I have a problem in calling a template class I have. I declared a new type name Array, which is a template;
在 .hpp 文件中:
In the .hpp file:
template <typename T>
class Array
{
public:
Array();
};
在 .cpp 文件中:
In the .cpp file:
template <typename T>
Array<T>::Array()
{
//Do something
}
主要內容:
Array<int> arr;
我收到鏈接錯誤:未解析到構造函數的外部符號.
I get Linkage error: unresolved external symbol to the ctor.
有什么想法嗎?
推薦答案
模板函數,包括成員函數,必須完全寫在頭文件中.這意味著如果你有一個模板類,它的實現必須完全在一個頭文件中.這是因為編譯器需要訪問整個模板定義(不僅僅是簽名),以便為模板的每個實例化生成代碼.
Template functions, including member functions, must be written entirely in the header files. This means that if you have a template class, its implementation must be entirely in a header file. This is because the compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template.
這篇關于C++ 模板,鏈接錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!