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");
}