C++模板

1. 函数模板

    目的:使用模板的目的就是能够让程序员编写与类型无关的代码。

 语法格式:
//class 可以与 typename 互换
template <class 形参名,class 形参名,......> 返回类型 函数名(参数列表)
{
    函数体
}

   示例:

#include <iostream>
using namespace std;
//template 关键字告诉C++编译器 要开始泛型编程了
//T - 参数化数据类型
template <typename T>
T Max(T a, T b) {
    return a > b ? a : b;
}
int main(void) { int n = 1; int m = 2; cout << "max(1, 2) = " << Max(n, m) << endl;
float a = 2.0; float b = 3.0; cout << "max(2.0, 3.0) = " << Max(a, b) << endl; char i = 'a'; char j = 'b'; cout << "max('a', 'b') = " << Max(i, j) << endl; return 0; }

2. 类模板

  目的:一个类模板(类生成类)允许用户为类定义个一种模式,使得类中的某些数据成员、默认成员函数的参数,某些成员函数的返回值,能够取任意类型(包括系统预定义的和用户自定义的)。

  语法格式:

template<class T>
class test
{
....
}

  示例:

template<class T>
class Test
{
private:
    T n;
    const T i;
public:
    Test():i(0) {}
    Test(T k);
    ~Test(){}

    void print();
    T operator+(T x);
};

   特殊:如果在类外定义成员函数,若此成员函数中有模板参数存在,则除了需要和一般类的类外定义成员函数一样的定义外,还需要在函数外进行模板声明。

template<class T>
Test<T>::Test(T k):i(k){ n=k;}

template<class T>
T Test<T>::operator+(T x){
    return n + x;
}

 参考文献:

1. https://blog.csdn.net/m0_53636439/article/details/119777817

2. https://www.cnblogs.com/cxq0017/p/6076856.html

3. https://www.runoob.com/w3cnote/c-templates-detail.html

posted @ 2022-11-10 09:30  二先生-  阅读(59)  评论(0)    收藏  举报