为什么fstream方法返回对“* this”的引用?

时间:2012-03-29 20:42:35

标签: c++ std fstream

我最近开始使用C ++进行编码,但是我很长时间用C语言编写。所以我正在阅读fstream类中的方法,并且我发现每个可能是一个过程的方法(什么都不返回)是返回对调用其方法的对象的引用。 (例如fstream& fstream :: read(char_type * __s,streamsize __n)。

为什么这样做?

我在fstream类的顶部编写了一个小层,所以我想知道我是否应该在我的读取方法中返回一个引用。

感谢。

3 个答案:

答案 0 :(得分:6)

返回对流对象本身的引用为您提供了一种检查 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 */ }

特别注意第二个例子中的重复调用:每次提取都返回对流对象的引用,因此我们可以在一个语句中连接多个提取,如果任何它们失败,整个操作将评估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;
}

答案 1 :(得分:5)

http://en.wikipedia.org/wiki/Method_chaining

https://isocpp.org/wiki/faq/references#method-chaining

这基本上就是为什么:

cout << "Hello " << "World"; 

作品。

(尽管正如Luchian Grigore指出的那样,cout不是一个fstream。虽然同样的想法适用,但他的回答提供了一个fstream的例子。)

答案 2 :(得分:4)

这样你可以使用 method chaining

stream << "foo";
stream << "bar";

可以替换为

stream << "foo" << "var";
相关问题