zoukankan      html  css  js  c++  java
  • 模板——函数模板

    //《C++编程——数据结构与程序设计方法》例15.8

    //利用函数重载技术,求两个整数、字符、浮点数或字符串中的较大值,需要编写4个函数larger。
    //而C++通过提供函数模板,简化了重载函数据的过程。

    #include <iostream>
    using namespace std;

    template<class Type>//Type,模板的形参,用于确定函数的形参,返回值类型,还用于在函数中声明变量。
    Type larger(Type x,Type y);

    int main()
    {
     cout<<"Line 1: Larger of 5 and 6 ="<<larger(5,6)<<endl;
     //由于5和6是int类型,编译器会自动用int取代Type,产生相应代码,以下同理。
     cout<<"Line 2: Larger of A and B ="<<larger('A','B')<<endl;
     cout<<"Line 3: Larger of 5.6 and 3.2 ="<<larger(5.6,3.2)<<endl;

     char str1[]="Hello";
     char str2[]="Happy";

     cout<<"Line 6: Larger of "<<str1<<" and "<<str2<<" = "<<larger(str1,str2)<<endl;

     return 0;
    }

    template<class Type>
    Type larger(Type x,Type y)
    {
     if(x>=y)
      return x;
     else
      return y;
    }

  • 相关阅读:
    Jzoj4729 道路修建
    Jzoj4727 挺进
    Jzoj4727 挺进
    Jzoj4726 种花
    Jzoj4726 种花
    Jzoj4725 素数序列
    Jzoj4725 素数序列
    力扣算法题—040组合求和二
    力扣算法题—039组合求和
    力扣算法题—038报数
  • 原文地址:https://www.cnblogs.com/java20130723/p/3211698.html
Copyright © 2011-2022 走看看