C++类模板实现push_back、insert、operator=

来源:互联网 发布:java怎样显示输入框 编辑:程序博客网 时间:2024/06/06 01:55

1、定义一个类模板:

template<class 模板参数表>
class 类名{


// 类定义......

};

template 是声明类模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个,可以是类型参数 ,也可以是非类型参数。类型参数由关键字class或typename及其后面的标识符构成。非类型参数由一个普通参数构成,代表模板定义中的一个常量。

2、代码实现:

// templatepeoject.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <stdlib.h>
#include <vector>
#include <iostream>
using namespace std;
template<class T>
class TemVector{
public:
TemVector(T i){}
void push_back(T i){
m_v.push_back(i);
}
void insert(T i){
m_v.insert(m_v.end(),i);
}
T operator= (T n){m_v = n;}
public:
std::vector<int> m_v;
};
int _tmain(int argc, _TCHAR* argv[])
{
TemVector<int> Tem(10);
std::vector<int> nV;
nV.push_back(1);
Tem.m_v = nV;
Tem.push_back(11);
Tem.insert(12);

int size = Tem.m_v.size();
for ( int n = 0; n < size; n++ )
{
cout << Tem.m_v.at(n) << endl;
}
system("pause");
return 0;
}

3、程序结果:


0 1