欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > 【C++ Primer Plus习题】8.6

【C++ Primer Plus习题】8.6

2025/4/3 3:32:35 来源:https://blog.csdn.net/qq_74047911/article/details/141790813  浏览:    关键词:【C++ Primer Plus习题】8.6

问题:

这里是引用

解答:

#include <iostream>
using namespace std;template <typename T>
T maxn(T arr[], int len)//通用
{T max = 0;for (int i = 0; i < len; i++){if (max < arr[i]){max = arr[i];}}return max;
}template<>
const char* maxn<const char*>(const char* c[], int len)
{const char* p = c[0];int size = strlen(p);for (int i = 1; i < len; i++){if (size < strlen(c[i])){p = c[i];}}return p;
}int main()
{int max = 0;double max1 = 0.0;int a1[6] = { 1,2,3,4,5,6 };double d1[4] = { 1.1,2.2,3.3,4.4 };max = maxn(a1, 6);max1 = maxn(d1, 4);cout << "int中最大的数为:" << max <<endl;cout << "double中最大的数为:" << max1 << endl;const char* p[5] = { "1","12","123","1234","12345" };const char* c= maxn(p, 5);cout << "字符数组中最长的字符为:" << c << endl;return 0;
}

运行结果:
在这里插入图片描述

考查点:

  • 模版函数
  • 模版函数具体化

注意:

  • 模版函数具体化会被优先调用
  • 可以自定义一些通用模版函数做不到的.
    在这里插入图片描述

2024年9月1日21:54:55

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com