C++大学教程(第七版)Chapter14.2函数模板-fig14_01

函数模板,打印数组。

用关键字typename 指出函数模板形参 ,实际上就是指任何内置类型。

template <typename T> 这样就是表示 T是个某个类型,是作为模板来使用的。

// Fig14_01_printArray.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;

//function template printArray definition
template <typename T>
void printArray(const T* const array, int count)
{
    for (int i = 0; i < count; i++)
        cout << array[i] << "  ";
    cout << endl;
}//end function template printArray 


int main()
{
    const int aCount = 5;// size of array a
    const int bCount = 7;// size of array b
    const int cCount = 6;// size of array c

    int a[aCount] = {1,2,3,4,5};
    double b[bCount] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7 };
    char c[cCount] = { "Hello" };//6th position for null 
    cout << "Array a contains:" << endl;

    //call integer function-template specialization 
    printArray(a,aCount);

    // double function-template specialization
    cout << "Array b contains:" << endl;
    printArray(b,bCount);

    //char function-template specialization
    cout << "Array c contains:" << endl;
    printArray(c,cCount);
}


运行结果:

Array a contains:
1  2  3  4  5
Array b contains:
1.1  2.2  3.3  4.4  5.5  6.6  7.7
Array c contains:
H  e  l  l  o

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值