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;
}
相关推荐
ONE_PUNCH_Ge12 小时前
Go 语言变量
开发语言
幼稚园的山代王12 小时前
go语言了解
开发语言·后端·golang
晚风残12 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer
杨云强12 小时前
离散积分,相同表达式数组和公式
算法
地平线开发者12 小时前
征程 6 | BPU trace 简介与实操
算法·自动驾驶
满天星830357712 小时前
【C++】AVL树的模拟实现
开发语言·c++·算法·stl
weixin_4569042712 小时前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
ss27312 小时前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
Lris-KK13 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
Mr_WangAndy13 小时前
C++设计模式_行为型模式_责任链模式Chain of Responsibility
c++·设计模式·责任链模式·行为型模式