C++函数模板与类模板

一、函数模板
1. 通用表达式(定义函数模板):

template<class T1, class T2>返回类型 函数名(参数列表){函数体}
//这里的模板参数列表类型class也可以用typename来表示

2.实例化
函数名(参数表),如

//定义一个函数模板
template<class T> T fun(T a, T b)
{
    return (a > b )? a : b;
}

//定义主函数
int main()
{
    cout << fun(3, 2) << endl;
    cout << fun(2.3, 4.6) << endl;
    return 0;
}

二、类模板
1.定义通用表达式

template<class T1, class T2> class 类名{};

2.类外定义类函数

template<class T1, class T2> 函数返回类型 类名<T1, T2>::函数名(函数参数列表){函数体}

3.实例化
类名<参数列表> 对象名;
对象名.类成员变量/成员函数;//就可以访问了

4.代码示例

//定义一个类模板myclass
template<class t1, class t2> class myclass
{
public:
    myclass();
    ~myclass();
    t1 show(t1 x, t2 y);

private: 
};

//定义类模板内的构造函数,析构函数和成员函数show,这里注意构造函数和析构函数没有返回值
template<class t1, class t2> myclass<t1, t2>::myclass()
{
    cout << "构造函数" << endl;
//  return 0;
}

template<class t1, class t2> myclass <t1, t2>::~myclass()
{
    cout << "析构函数" << endl;
//  return 0;
}
//这里注意要有返回return 0;
template<class t1, class t2> t1 myclass<t1, t2>::show(t1 x, t2 y) 
{
    cout << "show what?!" << x << "\t" << "t2 is " << y << endl;
    return 0;
}

//实例化对象hehe
int main()
{
    myclass<int, string> hehe;
    hehe.show(10, "hello");
    return 0;
}

三、综合应用函数模板和类模板的实例

/*函数模板和类模板
函数模板针对参数类型不同的函数;
类模板针对数据成员和成员函数类型不同的类;
利用模板原因是为了写出与类型无关的代码;
模板的声明和定义只能在全局,命名空间或类范围内进行。不能在局部,函数内进行,比如不能在main函数中声明和定义一个模板;
*/
#include "stdio.h"
#include"iostream"
#include"string"
using namespace std;
//函数模板
//这里class表示类型,也可以用typename来表示。
/*函数模板通用表达式
template <class 参数1, class 参数2, ... class 参数n> 返回类型 函数名(参数列表)
{     函数体    }
*/


template<class T> T fun(T a, T b)
{
    return (a > b )? a : b;
}


//类模板
/*
通用表达式:
template <class 参数1, class 参数2, ...class 参数n> class 类名
{};
*/
//构造函数和析构函数没有返回类型,c++规定每个类中必须要有
template<class t1, class t2> class myclass
{
public:
    myclass();
    ~myclass();
    t1 show(t1 x, t2 y);

private: 

};


//对类模板类的函数进行类外定义
/*通用格式:template<class T1, class T2> 函数返回类型 类名<模板参数名>::函数名(参数列表){函数体}*/

template<class t1, class t2> myclass<t1, t2>::myclass()
{
    cout << "构造函数" << endl;
//  return 0;
}

template<class t1, class t2> myclass <t1, t2>::~myclass()
{
    cout << "析构函数" << endl;
//  return 0;
}

template<class t1, class t2> t1 myclass<t1, t2>::show(t1 x, t2 y) 
{
    cout << "show what?!" << x << "\t" << "t2 is " << y << endl;
    return 0;
}
int main()
{
    cout << fun(3, 2) << endl;
    cout << fun(2.3, 4.6) << endl;
//实例化模板类,注意类模板是一个模板,模板类是一个类
    myclass<int, string> hehe;
    hehe.show(10, "hello");
    return 0;
}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值