C++函数模板与类模板


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

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

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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

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

2.类外定义类函数

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

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

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

/*函数模板和类模板
函数模板针对参数类型不同的函数;
类模板针对数据成员和成员函数类型不同的类;
利用模板原因是为了写出与类型无关的代码;
模板的声明和定义只能在全局,命名空间或类范围内进行。不能在局部,函数内进行,比如不能在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;
}

猜你喜欢

转载自blog.csdn.net/Windgs_YF/article/details/80912010