为什么文件读取函数中有额外的括号? [英] Why are extra parenthesis in file read function?
问题描述
我了解以下代码(从此处) )用于读取文件的字符串内容:
#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>());
为什么需要这么多括号来编译?
<因为没有圆括号,编译器将其视为一个函数声明,声明一个名为
content
的函数,返回 std :: istreambuf_iterator< char>
命名为 a std :: string
ifs
和一个无参参数,它是一个不带返回 std :: istreambuf_iterator< char>
的参数的函数。 你可以使用括号,或者作为Alexandre在注释中注释,你可以使用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>());
I understand that the following code (from here) is used to read the contents of a file to string:
#include <fstream>
#include <string>
std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
However, I don't understand why such seemingly redundant parentheticals are required. For example, the following code does not compile:
#include <fstream>
#include <string>
std::ifstream ifs("myfile.txt");
std::string content(std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>() );
Why are so many parentheses are needed for this to compile?
Because without the parentheses, the compiler treats it as a function declaration, declaring a function named content
that returns a std::string
and takes as arguments a std::istreambuf_iterator<char>
named ifs
and a nameless parameter that is a function taking no arguments that returns a std::istreambuf_iterator<char>
.
You can either live with the parens, or as Alexandre notes in the comments, you can use the uniform initialisation feature of C++ which has no such ambiguities:
std::string content { std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
Or as Loki mentions:
std::string content = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
这篇关于为什么文件读取函数中有额外的括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!