编译器不喜欢下面的主程序
int get1(ifstream &f){
int count;
f >> count;
return count;
}
int main(int argc, char** argv){
cout << get1(ifstream(argv[1])) << endl;
}
错误信息是:
test.cpp: In function 'int main(int, char**)':
test.cpp:11:33: error: invalid initialization of non-const reference of type 's\
td::ifstream& {aka std::basic_ifstream<char>&}' from an rvalue of type 'std::if\
stream {aka std::basic_ifstream<char>}'
test.cpp:4:5: error: in passing argument 1 of 'int get1(std::ifstream&)'
如果主程序写为
int main(int argc, char** argv){
ifstream f(argv[1]);
cout << get1(f) << endl;
}
有没有办法使紧凑的第一种形式起作用?