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;
}
有一種使緊湊的第一種形式工作的方法?
儘管我很不情願提及它,但因爲它絕對很糟糕,所以有一種方法:MSVC的惡意擴展。 – chris
@chris是的,我猶豫了一提,但最後決定不要:叫我迂腐,但這不是C++了。 – syam
我不確定,但沒有通過r-reference解決方案? – soon