【问题标题】:Why are extra parenthesis in file read function?为什么文件读取函数中有额外的括号?
【发布时间】:2012-09-25 19:49:10
【问题描述】:

我了解以下代码(from here)用于将文件内容读取为字符串:

#include <fstream>
#include <string>

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

但是,我不明白为什么需要这些看似多余的括号。例如,以下代码无法编译:

#include <fstream>
#include <string>

  std::ifstream ifs("myfile.txt");
  std::string content(std::istreambuf_iterator<char>(ifs),
                      std::istreambuf_iterator<char>()    );

为什么编译需要这么多括号?

【问题讨论】:

标签: c++ compiler-errors ifstream


【解决方案1】:

因为没有括号,编译器将其视为一个函数声明,声明一个名为 content 的函数,该函数返回一个 std::string,并将一个名为 ifsstd::istreambuf_iterator&lt;char&gt; 和一个作为函数的无名参数作为参数不接受返回 std::istreambuf_iterator&lt;char&gt; 的参数。

您可以使用括号,或者正如亚历山大在 cmets 中指出的那样,您可以使用没有这种歧义的 C++ 的统一初始化功能:

std::string content { std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };

或者正如 Loki 提到的:

std::string content = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());

【讨论】:

  • 注意:在 C++11 中你可以做std::string content{std::istreambuf_iterator&lt;char&gt;(ifs), std::istreambuf_iterator&lt;char&gt;()};
  • 或者你可以使用:std::string content = std::string( std::istreambuf_iterator&lt;char&gt;(ifs), std::istreambuf_iterator&lt;char&gt;());
  • 甚至auto content = std::string(std::istreambuf_iterator&lt;char&gt;(ifs), std::istreambuf_iterator&lt;char&gt;());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 2022-01-05
  • 2018-05-09
  • 1970-01-01
相关资源
最近更新 更多