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;
}
相关推荐
NAGNIP4 分钟前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
端平入洛7 小时前
delete又未完全delete
c++
颜酱8 小时前
单调栈:从模板到实战
javascript·后端·算法
CoovallyAIHub12 小时前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub12 小时前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub12 小时前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉
CoovallyAIHub12 小时前
强化学习凭什么比监督学习更聪明?RL的“聪明”并非来自算法,而是因为它学会了“挑食”
深度学习·算法·计算机视觉
CoovallyAIHub12 小时前
YOLO-IOD深度解析:打破实时增量目标检测的三重知识冲突
深度学习·算法·计算机视觉
NAGNIP1 天前
轻松搞懂全连接神经网络结构!
人工智能·算法·面试
NAGNIP1 天前
一文搞懂激活函数!
算法·面试