我是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感谢您的参考。我将不得不进一步详细研究模板。 –