函数重载 - 两个函数仅与默认参数不同 [英] Function overloading -- two functions only differ by a default parameter
问题描述
class A{
public:
void foo(int x)
{
cout << "foo with one\n";
}
void foo(int x, int y=10)
{
cout << "foo with two\n";
}
};
int main()
{
A a;
a.foo(1); //error?
}
所以,为什么我不能重载 void foo
So, why can't I overload void foo(int)
with a function that takes a default parameter?
推荐答案
没有你不能重载函数正在传递的参数的值的基础,因此也不允许基于默认参数的值重载。
No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either.
您只能在以下基础上重载函数:
You can only overload functions only on the basis of:
- 参数个数
- 参数序列
-
const
和volatile
。
- Type of arguments
- Number of arguments
- Sequence of arguments &
- Qualifiers like
const
andvolatile
.
编译器接受重载取决于事实:
如果编译器明确地解析了函数的调用。
Ofcourse, Whether the overload is accepted by the compiler depends on the fact:
If the compiler resolve calling of the function unambiguously.
在你的情况下,编译器不能解决歧义,例如:如果你简单地调用函数,编译器不知道调用哪个重载函数:
In your case, the compiler cannot resolve the ambiguity, for ex: The compiler wouldn't know which overloaded function to call if you simple called the function as:
foo(100);
编译器无法做出决定,因此无法执行错误。
The compiler cannot make the decision and hence the error.
这篇关于函数重载 - 两个函数仅与默认参数不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!