代码之家  ›  专栏  ›  技术社区  ›  Ocasta Eshu

为什么文件读取函数中有额外的括号?

  •  7
  • Ocasta Eshu  · 技术社区  · 12 年前

    我理解以下代码( 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>()    );
    

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

    1 回复  |  直到 8 年前
        1
  •  12
  •   Seth Carnegie    12 年前

    因为没有括号,编译器将其视为函数声明,声明一个名为 content 返回一个 std::string 并将a作为自变量 std::istreambuf_iterator<char> 命名的 ifs 和一个无名参数,该参数是一个不带参数的函数,返回 std::istreambuf_titerator<字符>

    你可以使用parens,或者正如Alexandre在评论中指出的那样,你可以使用C++的统一初始化功能,它没有这样的歧义:

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

    或者正如洛基提到的:

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