初学函数重载的菜鸟问题。。。

软件和网站开发以及相关技术探讨
回复
feirainy
帖子: 9
注册时间: 2009-07-03 18:52

初学函数重载的菜鸟问题。。。

#1

帖子 feirainy » 2010-11-29 20:16

代码: 全选

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <typename elemtype>
elemtype max(elemtype elem1, elemtype elem2)
{
        if (elem1 > elem2)
                return elem1;
        else
                return elem2;
}

int main()
{
        int num1 = 4, num2 = 5;
        cout << max(num1, num2);

        return 0;
}
编译后报错:
test.cpp: In function ‘int main()’:
test.cpp:18: 错误: 调用重载的‘max(int&, int&)’有歧义
test.cpp:7: 附注: 备选为: elemtype max(elemtype, elemtype) [with elemtype = int]
/usr/include/c++/4.3/bits/stl_algobase.h:210: 附注: const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]

请指教~~
feirainy
帖子: 9
注册时间: 2009-07-03 18:52

Re: 初学函数重载的菜鸟问题。。。

#2

帖子 feirainy » 2010-11-29 20:23

似乎跟库函数max冲突了。。。因为我把max函数的名字改了以后就可以了~~ :em06

可是是哪个头文件导致的?~~
feirainy
帖子: 9
注册时间: 2009-07-03 18:52

Re: 初学函数重载的菜鸟问题。。。

#3

帖子 feirainy » 2010-12-03 20:30

自顶一下~~ :em02
kanger
帖子: 86
注册时间: 2011-11-19 18:29
系统: 12.10

Re: 初学函数重载的菜鸟问题。。。

#4

帖子 kanger » 2014-01-22 11:23

一般这样才会出现有歧义:

代码: 全选

#include <stdio.h>
#include <string.h>

int func(int x, int c = 0)
{
	return x;
}
int func(int x)
{
	return x;
}


int main(int argc, char *argv[])
{
	int c = 0;
	
	c = func(1);
	
	printf("c = %d\n", c);

	return 0;
}

默认参数遇上了重载的问题。
回复