【发布时间】:2011-04-21 06:29:54
【问题描述】:
可能的重复: Why does std::string not provide a conversion to const char*? Why doesn't std::string provide implicit conversion to char*?
case 1 :
void readFile ( const string& inputfile ) {
ifstream in ( inputfile );
}
case 2:
void readFile ( const string& inputfile ) {
ifstream in ( inputfile . c_str() );
}
当然,我知道如何使用必需参数调用ifstream,但是C++ 字符串和以空字符结尾的字符序列(C 字符串).c_str() 之间的真正区别是什么?**
我认为自动类型转换应该发挥作用,即自动将 C++ 字符串转换为 .c_str()。我错了吗?
案例 1 出错,案例 2 工作正常。是否可以使用static_cast<> 将案例 1 转换为案例 2?
【问题讨论】:
-
文件流构造函数过去只接受一个 const char*,因此如果您使用字符串,则必须调用 c_str()。然而,在新的 C++0x 标准中,他们已经修复了这个问题,所以案例 1 将是有效的