类模板使用问题


前两天刚学了类模板,今天刚好想要用用它,结果出现了很多的错误,这里总结一个。

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值