zoukankan      html  css  js  c++  java
  • 模板(1)

    /*模板(1)*/

    #include "stdafx.h"
    #include <iostream.h>
    #include <string.h>

    class A
    {
        int m_nData;
    public:
        A(int nData ) : m_nData(nData)
        {
        }
        //
    重载 >
        int operator>( const A& Obj )
        {
            return (m_nData > Obj.m_nData);
        }
        //
    友元函数,重载 <<         cout的引用    cout后面跟的参数
        friend ostream &operator<<(ostream &out, const A &Obj);
    };

    ostream &operator<<(ostream &out, const A &Obj)
    {
        out << Obj.m_nData << endl;
        return out;
    }

    //
    函数模板 T为函数模板的类型参数

    //
    模板的实例化函数(模板) ----> 模板(函数)
    //
    编译器在发现有函数调用的时候,
    //
    会为此模板生成一个相应类型的模板函数(max_int)
    //
    一般引用好一些
    template<typename T1>
    T1 &max(T1 &a, T1 &b)
    {
        return a > b ? a : b;
    }

    //
    模板的重载 
    template<typename T1>
    T1 &max(T1 &a, T1 &b, T1 &c)
    {
        T1 max1 = a > b ? a : b;
        return max1 > c ? max1 : c;
    }

    //
    模板特化: 对某种类型的特殊处理函数
    char *max(char *p1, char *p2, char *p3)
    {
        char *pMax = strcmp(p1, p2) > 0 ? p1 : p2;
        return strcmp(pMax, p3) > 0 ? pMax : p3;
    }

    //
    模板特化: 对某种类型的特殊处理函数
    char *max(char *p1, char *p2)
    {
        int n = strcmp(p1 ,p2);
        return n > 0 ? p1 : p2;
    }

    int main(int argc, char* argv[])
    {
        int i = 1;
        int j = 2;
        char *pStr1 = "Hello";
        char *pStr2 = "Wolrd";
        char *pStr3 = "Template";
       
        //
    模板特化函数的调用
        cout << max(pStr1, pStr2, pStr3) << endl;
       
        //
    当模板参数个数只有一个,两种写法一样
        cout << max(i, j) << endl;
       
        //
    当外部有匹配的函数时候,优先调用
        cout << max<int>(i, j) << endl;
       
        char ch = 'A';
       
        cout << max<char>((char&)i, ch) << endl;
       
       
        //?max@@YAHHH@Z
        cout << max(1, 2) << endl;
       
        cout << max(2, 1) << endl;
       
        //?max@@YAMMM@Z
        cout << max(1.0f, 2.0f) << endl;
       
        A thea(10), theb(20);
       
        //?max@@YA?AVA@@V1@0@Z
        cout << max(thea, theb) << endl;
       
        return 0;
    }

  • 相关阅读:
    python 编码与解码
    python 写文件
    python 文件读写
    python 异常处理
    python 断言
    C++的可移植性和跨平台开发
    Python中subprocess学习
    Python 的web自动化测试
    CookieJar和HTTPCookieProcessor
    python3爬虫
  • 原文地址:https://www.cnblogs.com/w413133157/p/1663977.html
Copyright © 2011-2022 走看看