C++代码错误解决1(函数模板)

1、代码如下

复制代码
//示例函数模板的使用
#include <iostream>
#include <string>
using namespace std;
template <typename T>//函数模板
T max(T a,T b)
{
	return a>b?a:b;
} 
int main()
{
	int a,b;
	cout<<"input two integers to a&b:"<<endl;
	cin>>a>>b;
	cout<<"max("<<a<<","<<b<<")="<<max(a,b)<<endl;
	
	char c,d;
	cout<<"input two chars to c&d"<<endl;
	cin>>c>>d;
	cout<<"max("<<"\'"<<c<<"\'"<<","<<"\'"<<d<<"\'"<<")=";
	cout<<max(c,d)<<endl;
	
	float x,y;
	cout<<"input two floats to x&y:"<<endl;
	cin>>x>>y;
	cout<<"max("<<x<<","<<y<<")="<<max(x,y)<<endl;
	
	string p,h;
	cout<<"input two strings to p&h:"<<endl;
	cin>>p>>h;
	cout<<"max("<<"\'"<<p<<"\'"<<","<<"\'"<<h<<"\'"<<")=";
	cout<<max(p,h)<<endl;
	
	return 0;
}

2、报错如下

3、报错原因:

代码中使用了一个函数模板 max,但是在 C++ 中已经有一个名为 max 的标准库函数,用于比较两个值并返回较大的那个。因此,编译器无法确定到底是要调用自己定义的函数模板还是标准库的 max 函数。

4、解决办法:

1、将函数模板 max 重命名为其他名称,以避免与标准库函数冲突

2、在调用自己的函数模板时,使用作用域解析运算符 :: 来明确指定你要调用的是你自己定义的函数模板,而不是标准库的 max 函数。

方法一:

方法二:

5、这里我用方法一,修改后的代码如下:

复制代码
//示例函数模板的使用
#include <iostream>
#include <string>
using namespace std;
template <typename T>//函数模板
T my_max(T a,T b)
{
	return a>b?a:b;
} 
int main()
{
	int a,b;
	cout<<"input two integers to a&b:"<<endl;
	cin>>a>>b;
	cout<<"max("<<a<<","<<b<<")="<<my_max(a,b)<<endl;
	
	char c,d;
	cout<<"input two chars to c&d"<<endl;
	cin>>c>>d;
	cout<<"max("<<"\'"<<c<<"\'"<<","<<"\'"<<d<<"\'"<<")=";
	cout<<my_max(c,d)<<endl;
	
	float x,y;
	cout<<"input two floats to x&y:"<<endl;
	cin>>x>>y;
	cout<<"max("<<x<<","<<y<<")="<<my_max(x,y)<<endl;
	
	string p,h;
	cout<<"input two strings to p&h:"<<endl;
	cin>>p>>h;
	cout<<"max("<<"\'"<<p<<"\'"<<","<<"\'"<<h<<"\'"<<")=";
	cout<<my_max(p,h)<<endl;
	
	return 0;
}
相关推荐
fengfuyao985几秒前
基于MATLAB的GUI实现人脸检测、眼睛检测以及LBP直方图显示
开发语言·计算机视觉·matlab
你也向往长安城吗1 分钟前
推荐一个三维导航库:three-pathfinding-3d
javascript·算法
蒋星熠4 分钟前
C++零拷贝网络编程实战:从理论到生产环境的性能优化之路
网络·c++·人工智能·深度学习·性能优化·系统架构
百度智能云17 分钟前
VectorDB+FastGPT一站式构建:智能知识库与企业级对话系统实战
算法
CHANG_THE_WORLD17 分钟前
# C++ 中的 `string_view` 和 `span`:现代安全视图指南
开发语言·c++
雨落倾城夏未凉18 分钟前
9.c++new申请二维数组
c++·后端
Franklin39 分钟前
Python界面设计【QT-creator基础编程 - 01】如何让不同分辨率图像自动匹配graphicsView的窗口大小
开发语言·python·qt
雨落倾城夏未凉1 小时前
8.被free回收的内存是立即返还给操作系统吗?为什么?
c++·后端
雨落倾城夏未凉1 小时前
6.new和malloc的区别
c++·后端
郝学胜-神的一滴1 小时前
深入理解QFlags:Qt中的位标志管理工具
开发语言·c++·qt·程序人生