C++之把流对象当做函数参数传递
一、编译不通过的代码:
/******************************************************************************* * File Name : ./main.cpp * Author : zjw * Email : zjw_0722@163.com * Create Time : 2015年04月09日 星期四 17时36分02秒 *******************************************************************************/ #include <iostream> #include <fstream> #include <string> using namespace std; void Print(ostream out, string strText) { out << strText << endl; } int main(int argc, char **argv) { Print(cout, "cout"); ofstream fout("./test.dat"); if (!fout.is_open()) { Print(cout, "error"); } else { Print(fout, "fout"); fout.close(); } return 0; }
错误提示:
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/ios:39, from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/ostream:40, from /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iostream:40, from ./main.cpp:8: /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/ios_base.h: In copy constructor ‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’: /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/ios_base.h:790: 错误:‘std::ios_base::ios_base(const std::ios_base&)’是私有的 /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd:47: 错误:在此上下文中 /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd: In copy constructor ‘std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)’: /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/iosfwd:56: 附注:在这里第一次需要生成的方法‘std::basic_ios<char, std::char_traits<char> >::basic_ios(const std::basic_ios<char, std::char_traits<char> >&)’ ./main.cpp: In function ‘int main(int, char**)’: ./main.cpp:21: 附注:在这里第一次需要生成的方法‘std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)’ ./main.cpp:21: 错误: 初始化‘void Print(std::ostream, std::string)’的实参 1
二、可执行代码:
/******************************************************************************* * File Name : ./main.cpp * Author : zjw * Email : zjw_0722@163.com * Create Time : 2015年04月09日 星期四 17时36分02秒 *******************************************************************************/ #include <iostream> #include <fstream> #include <string> using namespace std; void Print(ostream &out, string strText) { out << strText << endl; } int main(int argc, char **argv) { Print(cout, "cout"); ofstream fout("./test.dat"); if (!fout.is_open()) { Print(cout, "error"); } else { Print(fout, "fout"); fout.close(); } return 0; }
编译&执行成功。
三、总结:
这里不明白的是为什么传递流对象不行,而传递引用可以。而且g++的编译错误信息又看不太懂。只能记住以后需要用到流对象做参数,使用传引用了。