我是C++新手,在解決我遇到的未定義引用問題時遇到困難。我試圖創建一個測試類,它作爲輸入數組構造函數,和一切似乎如果我把一切都位於一個文件,如下工作:C++未定義引用構造函數錯誤?
main.cpp
#include <iostream>
class Test
{
public:
template<typename T,int SIZE>
Test(T (&array)[SIZE]);
};
template<typename T,int SIZE>
Test::Test(T (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}
int main()
{
int myIntArray[10];
Test myTest(myIntArray);
return 0;
}
當我運行這個例子,我得到的以下的輸出:
Array constructor was called
Size of array is: 10
然而,當我打破了這個例子爲以下三個文件:
Test.h
class Test
{
public:
template<typename T,int SIZE>
Test(T (&array)[SIZE]);
};
Test.cpp的
#include "Test.h"
#include <iostream>
template<typename T,int SIZE>
Test::Test(T (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}
的main.cpp
#include "Test.h"
#include <iostream>
int main()
{
int myIntArray[10];
Test myTest(myIntArray);
return 0;
}
我收到an undefined reference to Test::Test<int, 10>(int (&) [10])'
。我不完全確定我做錯了什麼,並且正在想我可能忽略了一些事情。任何洞察力將不勝感激。感謝您的幫助。
請參閱http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – clcto
@clcto感謝您的參考。我將不得不進一步詳細研究模板。 –