C++模板

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++模板

我是小白呀   2022-05-22 我要评论

概述

模板可以帮助我们提高代码的可用性, 可以帮助我们减少开发的代码量和工作量.

在这里插入图片描述

函数模板

函数模板 (Function Template) 是一个对函数功能框架的描述. 在具体执行时, 我们可以根据传递的实际参数决定其功能. 例如:

int max(int a, int b, int c){
    a = a > b ? a:b;
    a = a > c ? a:c;

    return a;
}

long max(long a, long b, long c){
    a = a > b ? a:b;
    a = a > c ? a:c;

    return a;
}

double max(double a, double b, double c){
    a = a > b ? a:b;
    a = a > c ? a:c;

    return a;
}

写成函数模板的形式:

template<typename T>
T max(T a, T b, T c){
    a = a > b ? a:b;
    a = a > c ? a:c;

    return a;
}

类模板

类模板 (Class Template) 是创建泛型类或函数的蓝图或公式.

#ifndef PROJECT2_COMPARE_H
#define PROJECT2_COMPARE_H

template <class numtype>  // 虚拟类型名为numtype
class Compare {
private:
    numtype x, y;
public:
    Compare(numtype a, numtype b){x=a; y=b;}
    numtype max() {return (x>y)?x:y;};
    numtype min() {return (x < y)?x:y;};
};

mian:

int main() {

    Compare<int> compare1(3,7);
    cout << compare1.max() << ", " << compare1.min() << endl;

    Compare<double> compare2(2.88, 1.88);
    cout << compare2.max() << ", " << compare2.min() << endl;

    Compare<char> compare3('a', 'A');
    cout << compare3.max() << ", " << compare3.min() << endl;

    return 0;

}

输出结果:

7, 3
2.88, 1.88
a, A

模板类外定义成员函数

如果我们需要在模板类外定义成员函数, 我们需要在每个函数都使用类模板. 格式:

template<class 虚拟类型参数>
函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {}

类模板:

#ifndef PROJECT2_COMPARE_H
#define PROJECT2_COMPARE_H

template <class numtype>  // 虚拟类型名为numtype
class Compare {
private:
    numtype x, y;
public:
    Compare(numtype a, numtype b);
    numtype max();
    numtype min();
};

template<class numtype>
Compare<numtype>::Compare(numtype a,numtype b) {
    x=a;
    y=b;
}

template<class numtype>
numtype Compare<numtype>::max( ) {
    return (x>y)?x:y;
}

template<class numtype>
numtype Compare<numtype>::min( ) {
    return (x>y)?x:y;
}

#endif //PROJECT2_COMPARE_H

类库模板

类库模板 (Standard Template Library). 例如:

#include <vector>
#include <iostream>
using namespace std;


int main() {
    int i = 0;
    vector<int> v;
    for (int i = 0; i < 10; ++i) {
        v.push_back(i);  // 把元素一个一个存入到vector中
    }

    for (int j = 0; j < v.size(); ++j) {
        cout << v[j] << " ";  // 把每个元素显示出来
    }

    return 0;
}

输出结果:

0 1 2 3 4 5 6 7 8 9

抽象和实例

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们