以下是 learncpp.com 的模板类教程:
主.cpp
#include "Array.h"
int main()
{
Array<int> intArray(12);
Array<double> doubleArray(12);
for (int count = 0; count < intArray.getLength(); ++count)
{
intArray[count] = count;
doubleArray[count] = count + 0.5;
}
for (int count = intArray.getLength()-1; count >= 0; --count)
std::cout << intArray[count] << "t" << doubleArray[count] << 'n';
return 0;
}
Array.h
#ifndef ARRAY_H
#define ARRAY_H
#include <assert.h> // for assert()
template <class T>
class Array
{
private:
int m_length;
T *m_data;
public:
Array()
{
m_length = 0;
m_data = nullptr;
}
Array(int length)
{
m_data = new T[length];
m_length = length;
}
~Array()
{
delete[] m_data;
}
void Erase()
{
delete[] m_data;
// We need to make sure we set m_data to 0 here, otherwise it will
// be left pointing at deallocated memory!
m_data = nullptr;
m_length = 0;
}
T& operator[](int index)
{
assert(index >= 0 && index < m_length);
return m_data[index];
}
// The length of the array is always an integer
// It does not depend on the data type of the array
int getLength();
};
#endif
阵列.cpp
#include "Array.h"
template <typename T>
int Array<T>::getLength() { return m_length; }
错误:未解析的外部符号"public: int __thiscall Array::getLength(void(" (?GetLength@?$Array@H@@QAEHXZ(
说明:为了使编译器使用模板,它必须同时看到模板定义(而不仅仅是声明(和用于实例化模板的模板类型。另请记住,C++单独编译文件。当 Array.h 标头在 main 中 #included 时,模板类定义将复制到 main.cpp 中。当编译器看到我们需要两个模板实例 Array 和 Array 时,它将实例化这些实例,并将它们编译为 main .cpp 的一部分。但是,当它分别编译 Array .cpp时,它会忘记我们需要一个 Array 和 Array,因此模板函数永远不会实例化。因此,我们得到一个链接器错误,因为编译器找不到 Array::getLength(( 或 Array::getLength(( 的定义。
解释是什么意思? 我很难理解Alex(learncpp的创建者(提供的解释。
>// The length of the array is always an integer // It does not depend on the data type of the array int getLength();
数组的长度确实不依赖于数据类型。但是,Array<double>::getLength()
和Array<int>::getLength()
是两个不同的功能。仅当模板实例化被嵌入inline
时,才能为所有模板实例化实现getLength()
。因此,无法在.cpp文件中实现它。