我最近开始用C++编写代码,但我很长时间用C语言编写.所以我正在从fstream类中读取方法,并且我已经发现每个可能是一个过程的方法(什么都不返回)都返回一个引用到调用其方法的对象.(例如,fstream&fstream :: read(char_type*__s,streamsize __n)).
为什么这样做?
我在fstream类的顶部编写了一个小层,所以我想知道我是否应该在读取方法中返回一个引用.
谢谢.
返回对流对象本身的引用为您提供了一种检查 I/O操作有效性的绝佳方法:如果操作失败,则流对象处于失败状态,这意味着它将false在布尔上下文中求值.因此我们可以写:
while (std::getline(instream, str)) { /* ... process line ... */ }
if (anotherstream >> x >> y) { /* process x and y */ }
else { /* error, at least one extraction failed */ }
if (!laststream.read(buf, sizeof(buf)) { /* error */ }
Run Code Online (Sandbox Code Playgroud)
请特别注意第二个示例中的重复调用:每次提取都返回对流对象的引用,因此我们可以在一个语句中连接多个提取,如果其中任何一个提取失败,整个操作将进行评估false.
这是一个实际的例子,[x y z]从标准输入中解析表单的行:
for (std::string line; std::getline(std::cin, line); )
{
std::istringstream iss(line);
char l, r;
double x, y, z;
if (!(iss >> l >> x >> y >> z >> r) || (l != '[') || (r != ']'))
{
std::cerr << "Malformed line ('" << line << "'), skipping.\n";
continue;
}
std::cout << "You said: " << x << ", " << y << ", " << z << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
http://en.wikipedia.org/wiki/Method_chaining
https://isocpp.org/wiki/faq/references#method-chaining
这基本上就是为什么:
cout << "Hello " << "World";
Run Code Online (Sandbox Code Playgroud)
作品.
(尽管正如Luchian Grigore指出的那样,cout不是一个fstream.虽然同样的想法适用,但他的回答提供了一个fstream的例子.)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |