C++类模板
2016-02-13 20:49
423 查看
与函数模板相同,往往有时候对好几个功能相似的类,可以使用类模板。
C++类模板
#include <iostream>
using namespace std;
template<class numtype> //声明一个模板,虚拟类型名为numtype
class compare //类模板名为compare
{
public:
compare(numtype x,numtype y)
{
this->x=x;
this->y=y;
}
numtype max()
{
return x>y?x:y;
}
numtype min()
{
return x<y?x:y;
}
numtype mean();
private:
numtype x,y;
};
template<class numtype>
numtype compare<numtype>::mean()
{
return (x+y)/2;
}
int main()
{
compare<int> comp1(1,2);
cout << "max is" << comp1.max() << endl;
cout << "min is" << comp1.min() << endl;
compare<float> comp2(1.5,2.1);
cout << "max is" << comp2.max() << endl;
cout << "min is" << comp2.min() << endl;
cout << "mean is" << comp2.mean() << endl;
compare<char> comp3('a','b');
cout << "max is" << comp3.max() << endl;
cout << "min is" << comp3.min() << endl;
return 0;
}1.1在声明类模板前要增加一行 template<class 类型参数名>1.2 numtype只是一个虚拟类型参数名。1.3在建立对象时,如果指定为int则为int型,指定为float,则为float型。实现“一类多用”1.4因为类模板包含参数,所以被称为参数化的类。1.5如果说类是对象的抽象,那么类模板是类的抽象,类是类模板的实例。1.6使用类模板:compare <int> cmp1(1,2);1.7在类外使用类模板函数template <class numtype>numtype compare<numtype>::mean(){return (x+y)/2;}
C++类模板的使用步骤
1.1先写出一个实际的类,而不是类模板。1.2将此类中的int等改成一个指定的虚拟类型名。1.3在类的声明前加一行:template <class 虚拟化参数(如:numtype)>1.4用类模板定义对象时用以下形式:compare <int> comp1(1,2);1.5在模板外定义成员函数,应写成类模板的形式。template<class numtype>numtype compare<numtype>::mean(){}C++类模板其他
1.1类模板的类型参数可以有一个或者多个,每个类型前面都必须加class,如:template<class T1,class T2>class someclass{...};在定义对象的时候分别带入实际的类型名,如:someclass <int,double> obj;1.2和使用类一样,在使用类模板的时候要注意其作用域,只能在其有效作用域内用它定义对象。1.3模板可以有层次,一个类模板可以作为基类,派生出派生类的模板类。相关文章推荐
- neuq oj 1018 A+B again C语言
- VC++深入详解的函数总结
- VS2008下编译C++程序,找不到 stdint.h,原因及解决方案
- offsetof()
- C++友元
- 黑马程序员-C语言02
- C++静态成员
- 【C语言】C语言运算符
- 【C语言】C语言运算符
- leetcode70题 题解 翻译 C语言版 Python版
- C++对象的赋值和复制
- Windows 下免费的 C++ 开发平台 EasilyGCC 正式发布
- c++11 新特性之 autokeyword
- C++对象的动态建立和释放
- 【C语言】C语言static和extern区别
- 【C语言】C语言static和extern区别
- 【C语言】C语言外部变量和内部变量
- 【C语言】C语言外部变量和内部变量
- 【C语言】C语言局部变量和全局变量
- usaco 2.2.3 runround