【发布时间】:2021-04-06 22:44:44
【问题描述】:
为了了解更多使用指令和函数重载,我尝试了这个程序:
namespace ns{
void f(int){cout << "int\n";}
void f(double){cout << "double\n";}
void f(std::string){cout << "string\n";}
struct Foo{};
}
void f(ns::Foo const&){
cout << "ns::Foo\n";
}
namespace bin{
void f(int*){
std::cout << "bin::f(int*)\n";
}
}
int main(){
using namespace ns;
//using namespace bin;
f(7); // int
f(7.5); // double
f(ns::Foo{}); // ns::Foo
try{
f(nullptr);
}
catch(std::exception const& e){
std::cout << e.what() << std::endl;
}
}
当我运行程序时,它工作正常,除了最后一次调用f(nullptr) 导致运行时错误:
int
double
ns::Foo
basic_string::_M_construct null not valid
如果我取消注释命名空间 bin 的 using 指令,则代码可以正常工作。
using namespace bin;
输出:
int
double
ns::Foo
bin::f(int*)
【问题讨论】:
-
void f(std::string)将错误地尝试将char*转换为std::string。 -
不幸的是,您可以使用
f(0)做同样的事情。任何其他数字都将被编译器捕获为非法的整数到字符串的转换,但NULL和 0 之间的历史关系在此阻碍了。 -
使用命名空间 bin 时,您的 f(int*) 更匹配(无转换),然后字符串(const char*)错误这一事实并不重要。
标签: c++ overloading using-directives