前两天刚学了类模板,今天刚好想要用用它,结果出现了很多的错误,这里总结一个。
main文件包含的文件
对于模板的分文件编写问题,由于只是模板,编译时无法确定具体的类,因此不能将模板定义和实现分开来写,一种变通的方式是将cpp文件也include到main文件中,如下:
#include <iostream>
#include "src/Array.cpp"//注意不在同一路径下的文件要写路径
#include "Array.h"
int main()
{.........}
类模板内函数声明的格式
例如这是我今天写的一个代码的片段:
这里的函数声明和普通类的函数声明没有太大区别。
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
#include <vector>
using namespace std;
template<typename T,int size>
class Array
{
public:
int getsize();//数组长度
//===========================插入函数
bool back_add(const T);
bool head_add(const T);
bool _insert(int,const T);
~Array(){vec.clear();};
private:
vector<T> vec;
};
//==========================比较函数
template <class Type> bool comp(const Type&,const Type&);
#endif // ARRAY_H
这是我的类的实现文件
主要注意函数定义的格式
#include "Array.h"
template<class T,int size>
int Array<T,size>::getsize()//数组长度
{
return size;
}
//--------------------------------------------------------
//插入函数
template<class T,int size>
bool Array<T,size>::back_add(const T A)
{
if(vec.size()==size)
{
return false;
}
else
{
vec.push_back(A);
return true;
}
}
template<class T,int size>
bool Array<T,size>::head_add(const T A)
{
if(vec.size()==size)
{
return false;
}
else
{
vec.insert(vec.begin(),A);
return true;
}
}
template<class T,int size>
bool Array<T,size>::_insert(int a,const T A)
{
if(vec.size()==size)
{
return false;
}
else
{
typename vector<T>::iterator it;
it = vec.begin();
vec.insert(it+a,A);
}
}