【发布时间】:2016-10-05 06:31:12
【问题描述】:
以下程序可以正常编译并按预期工作。它的输出是:
1
2
#include <stdio.h>
class Foo
{
public:
void Bar(const char* b, ...) { printf("1\n"); };
void Bar(int a, const char* b, ...) { printf("2\n"); };
};
int main()
{
Foo foo1;
foo1.Bar("Test", "xx", 1, 2);
foo1.Bar(1, "xx", "xx", 2, 2);
}
现在,如果我将第二个 Bar 函数的 int 参数更改为 bool 并将 foo1.Bar(1, "xx", "xx", 2, 2); 更改为 foo1.Bar(true, "xx", "xx", 2, 2);,那么以下行将无法编译并且我得到错误:'Foo::Bar': 2 overloads have similar conversions:
foo1.Bar("Test", "xx", 1, 2);
没有编译的整个程序:
#include <stdio.h>
class Foo
{
public:
void Bar(const char* b, ...) { printf("1\n"); };
void Bar(bool a, const char* b, ...) { printf("2\n"); };
};
int main()
{
Foo foo1;
foo1.Bar("Test", "xx", 1, 2); // error: 'Foo::Bar': 2 overloads have similar conversions
foo1.Bar(true, "xx", "xx", 2, 2);
}
我不明白为什么第二种情况有歧义。
编辑
但是如果指针隐式转换为bool,为什么下面会编译?
#include <stdio.h>
class Foo
{
public:
void Bar(const char* b) { printf("1\n"); };
void Bar(bool a) { printf("2\n"); };
};
int main()
{
Foo foo1;
foo1.Bar("Test");
foo1.Bar(true);
}
【问题讨论】:
-
这与可变参数函数无关,如果你构建了一个 minimal 测试用例,你就会发现。
-
@LightnessRacesinOrbit 我刚刚编辑了问题并添加了一个最小的测试用例,没有编译的可变参数函数......
-
@robor78 问题相似但不一样。这里我们有
const char*,它是一个内置类型,而在另一个问题中有一个string,它是一个用户定义类型。 -
…………呸。