C++模板类的声明

C++的模板类感觉跟C#的泛型非常相似,自己写了个例子试试,结果一大堆错误,后来慢慢调试,发现模板类的声明和定义不能分开(必须在同一个文件中),否则在使用模板类的会报一个错误:“无法解析的外部符号......该符号在函数 _main 中被引用”。然后把函数的定义全部挪到类的声明里面去后,就可以了通过了。看了好多人的例子都不曾提到这点,所以和大家分享下。

下面是代码例子

--List.h文件

#include "iostream"
#pragma once

template<class T>
class List
{
public:
 List()
 {
  length=10;
  count = 0;
  p = new T[10];
 }
 bool Add(T obj)
 {
  
  if(count==length)
  {
   length+=10;
   T* temp = new T[length];
   for (int i=0;i<count;i++)
   {
    temp[i]=p[i];
   }
   delete []p;
   p=new T[length];
   for (int i=0;i<count;i++)
   {
    p[i]=temp[i];
   }
   delete []temp;
  }
  p[count] = obj;
  count++;
  return true;
 }
 bool Remove(T obj)
 {
  int index=-1;
  for(int i=0;i<count;i++)
  {
   if(typeid(p[i])==typeid(obj))
   {
    index =i;
   }
  }
  if(index!=-1)
  {
   for (int i=index+1;i<count;i++)
   {
    p[index] = p[index+1];
   }
   count--;
   T* temp = new T[count];
   for (int i=0;i<count;i++)
   {
    temp[i]=p[i];
   }
   delete []p;
   p=new T[length];
   for (int i=0;i<count;i++)
   {
    p[i]=temp[i];
   }
   delete []temp;
  }else
  {
  return false;
  }
  return true;
 }

 void prinfCount()
 {
  cout<<"元素个数为:"<<count<<endl;
 }
public:
 ~List(void)
 {
  delete[] p;
 }
private :
 T *p;
 int count;//元素个数
 int length;//数组长度
};


 

**********************main.cpp文件***********************

#include <iostream>
#include <windows.h>
#include "List.h"
using namespace std;
void main()
{

List<int> li;
 li.Add(5);
 li.Add(6);
li.Remove(5);
li.prinfCount();
 system("pause");


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值