C++_模板

来源:互联网 发布:计算机编程英语 编辑:程序博客网 时间:2024/05/17 23:21
// 模板#include <iostream>template<class Type>  // template<typename Type>/* template 模板类型关键字,template用于每个模板类型声明和定义的开头。 尖括号中的就是模板类型,也叫模板参数。 class关键字,表示该参数是一个类型,这个class与表示类的class没有关系。 Type是类型名,这个类型名可以随便起名 */void Tswap(Type &x, Type &y){    Type temp;    temp = x;    x = y;    y = temp;}int main(){    int x = 2, y = 5;    std::cout << "交换前,x:" << x << " y:" << y << std::endl;    Tswap(x, y);    std::cout << "交换后,x:" << x << " y:" << y << std::endl;        float a = 2.15f, b = 5.34f;    std::cout << "交换前,a:" << a << " b:" << b << std::endl;    Tswap(a, b);    std::cout << "交换后,a:" << a << " b:" << y << std::endl;        double c = 2.153456f, d = 5.347283f;    std::cout << "交换前,c:" << c << " d:" << d << std::endl;    Tswap(x, y);    std::cout << "交换后,c:" << c << " d:" << d << std::endl;            return 0;}

// 模板重载#include <iostream>template<class T>  // 原始模板void Tswap(T &x, T &y){    std::cout << "调用Tswap(T &x, T &y)函数" << std::endl;    T temp;    temp = x;    x = y;    y = temp;}template<class T>  // 模板重载(交换数据)void Swap(T x[], T y[], int n)  // 相当于void Swap(int x[], int y[], int n){    std::cout << "Swap(T &x[], T &y[], int n)" << std::endl;    T temp;    for(int i = 0; i < n ; i ++)    {        temp = x[i];        x[i] = y[i];        y[i] = temp;    }    /*    其实模板重载,就是编译器根据我们给模板传递的数据类型,使用模板模式重载了一个函数。    其实说来说去,都是一个目的,都是为了代码重用,提高效率    */}template<class T>  // 模板重载(显示数据)void show(T x[], T y[], int n)  // 相当于void show(int x[], int y[], int n){    for(int i = 0; i < n; i ++)    {        std::cout << "x[" << i << "]:" << x[i] << ",y[" << i << "]:" << y[i] << std::endl;    }}int main(){    int x = 2;    int y = 5;    std::cout << "交换前:x = " << x << ",y = " << y << std::endl;    Tswap(x,y);    std::cout << "交换后:x = " << x << ",y = " << y << std::endl;    int num1[10] = {10,11,12,13,14,15,16,17,18,19};    int num2[10] = {0,1,2,3,4,5,6,7,8,9};    std::cout << "交换前:" << std::endl;    show(num1,num2,10);    Swap(num1,num2,10);    std::cout << "交换后:" << std::endl;    show(num1,num2,10);    return 0;}
// 类模板#include <iostream>#include "Person.h"#include "Student.h"using namespace std;template<typename T1, typename T2>class rect{public:    void setValue(T1 &value1, T2 &value2)    {        x = value1;        y = value2;    }    T1 &getValue1()    {        return x;    }    T2 &getValue2()    {        return y;    }private:    T1 x;    T2 y;};int main(){    rect<int, float> myRect;    int a = 12;    float b = 2.0f;    myRect.setValue(a, b);    cout << "x:" << myRect.getValue1() << endl;    cout << "y:" << myRect.getValue2() << endl;    return 0;}
template <typename Type>  // 模板函数Type GetMax(Type a, Type b){    return (a > b ? a : b);}char *GetMax(char *a, char *b)  // 重载模板函数{    return (strcmp(a, b) > 0 ? a : b);}int main(int argc, const char * argv[]){    char p1[] = "C++";    char p2[] = "Hello";    cout << GetMax(p1, p2) << endl;        return 0;}










0 0