您的位置:首页 > 编程语言 > C语言/C++

c++模版笔记

2013-12-06 14:36 113 查看
一、一般模板函数形式

#include <iostream>
using namespace std;

//templae <typename type1,typename type2> //若有多个参参数可如此定义即可
template <typename type>//定义不定类型
const type& myMax(const type& valueOne,const type& valueTow)
{
if(valueOne >= valueTow)
return valueOne;
else
return valueTow;
}

int main()
{
int intOne = myMax(45,32);
double doubleOne = myMax(453.3,8923.9);

cout<<"intOne = "<<intOne<<endl;
cout<<"doubleTow = "<<doubleOne<<endl;

int s87;cin>>s87;
return 0;
}

上述代码在编译阶段,编译器其实是自动生成两个函数。模板原理由此可观一二

二、模板类

#include <iostream>
using namespace std;

template <typename type>//定义不定类型
class classOne
{
public:
static int staticValue;
};
template <typename type> int classOne<type>::staticValue;//static value init

int main()
{
classOne<int> intCase1,intCase2;
intCase1.staticValue = 100;

classOne<double> doubleCase1,doubleCase2;
doubleCase1.staticValue = 200.999;

cout<<"int class:staticValue="<<intCase2.staticValue<<endl;
cout<<"double clas:staticValue="<<doubleCase2.staticValue<<endl;
int s87;cin>>s87;
return 0;
}
由上可知,编译器是根据不同 的static创建了两个没有关联的类,一个是int型的一个是double型的,他们是连个不同类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: