问题
Given such a code segment:
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream file("1.txt");
string str((istream_iterator<char>(file)),istream_iterator<char>());
file.close();
cout<<str<<endl;
}
The code constructs a string from a file using istream_iterator.
Notice that the first parameter of string constructor is enclosed with a pair of parentheses. If I omit the parentheses, there will be an error. In VC++ 2008, a link error will come about. In G++, the code has a wrong output.
I feel very strange about the parentheses. What's the difference and why?
回答1:
Without the "extra" parentheses, you get C++'s "most vexing parse" -- instead of defining an object named str
with the two istream_iterators to specify its initializers, it's parsed as a declaration of a function named str
that returns a string
, and the "stuff" in parentheses specifies the types of parameters it takes.
回答2:
It looks like one of the examples for "C++ most vexing parse" problem. Looks like compiler is interpreting the statement with ()
as a function declaration of function str
which accepts two parameters. By adding ()
you are informing the compiler that it is an object and not part of function prototype signature.
来源:https://stackoverflow.com/questions/10039657/strange-error-in-using-templateclass-inputiterator-string-inputiterator-begin