【发布时间】:2014-04-07 05:13:52
【问题描述】:
我在 Visual Studio 编译器(在 VS2010 和 VS2012 中测试)出现了意外的重载解析行为。
小例子:
#include <iostream>
#include <string>
void f(void *)
{
std::cout << "f(void*)\n";
}
void f(const std::string &)
{
std::cout << "f(const std::string &)\n";
}
int main()
{
f("Hello World!");
}
输出:
> f(void *)
预期输出:
> f(const std::string &)
使用 GCC 编译(使用 4.6.3 测试)会生成预期的输出。
如果我注释掉 f() 的“const std::string &”版本,Visual Studio 会愉快地在 /W4 上编译而没有任何警告,而 GCC 会发出以下错误(如预期的那样):“来自 'const void 的无效转换*' 到 'void*' [-fpermissive]"。
有谁知道为什么 Visual Studio 会以这种方式运行,基本上选择 const 强制转换重载而不是转换为 char[] 的 std::string?
有没有办法禁止这种行为,或者至少让VS产生警告?
【问题讨论】:
标签: c++