为什么std :: fstream类不带std :: string? [英] Why don't the std::fstream classes take a std::string?
问题描述
这不是一个设计问题,真的,虽然它可能看起来像。 (好吧,好吧,这是一个设计问题)。我想知道的是为什么C ++ std :: fstream
类不采取 std :: string
它们的构造函数或开放方法。每个人都喜欢代码示例,因此:
This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ std::fstream
classes don't take a std::string
in their constructor or open methods. Everyone loves code examples so:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "testfile";
std::ifstream fin;
fin.open(filename.c_str()); // Works just fine.
fin.close();
//fin.open(filename); // Error: no such method.
//fin.close();
}
使用文件时,当然,C ++库将尽可能使用 std :: string
?
This gets me all the time when working with files. Surely the C++ library would use std::string
wherever possible?
推荐答案
通过使用C字符串C ++ 03 std :: fstream
类减少对 std :: string
类的依赖。然而,在C ++ 11中, std :: fstream
类允许传递 std :: string
构造函数参数。
By taking a C string the C++03 std::fstream
class reduced dependency on the std::string
class. In C++11, however, the std::fstream
class does allow passing a std::string
for its constructor parameter.
现在,你可能会想知道为什么没有从 std:string
一个C字符串,所以一个类,期望一个C字符串仍然可以采取 std :: string
就像一个类,期望一个 std :: string
可以接受C字符串。
Now, you may wonder why isn't there a transparent conversion from a std:string
to a C string, so a class that expects a C string could still take a std::string
just like a class that expects a std::string
can take a C string.
原因是这会导致转换周期,这反过来可能导致问题。例如,假设 std :: string
可以转换为C字符串,以便可以使用 std :: string
s与 fstream
s。还假设C字符串可以转换为 std :: string
s,就像当前标准中的状态一样。现在,考虑以下:
The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose std::string
would be convertible to a C string so that you could use std::string
s with fstream
s. Suppose also that C string are convertible to std::string
s as is the state in the current standard. Now, consider the following:
void f(std::string str1, std::string str2);
void f(char* cstr1, char* cstr2);
void g()
{
char* cstr = "abc";
std::string str = "def";
f(cstr, str); // ERROR: ambiguous
}
因为你可以在 std :: string
和C字符串调用 f()
可以解析为 f()
替代,因此是不明确的。解决方案是通过使一个转换方向显式来打破转换循环,这是STL选择使用 c_str()
。
Because you can convert either way between a std::string
and a C string the call to f()
could resolve to either of the two f()
alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with c_str()
.
这篇关于为什么std :: fstream类不带std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!