一、编译不通过的代码:
/*******************************************************************************
* 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 ;
}
错误提示:
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4./../../../../include/c++/4.4./ios:,
from /usr/lib/gcc/x86_64-redhat-linux/4.4./../../../../include/c++/4.4./ostream:,
from /usr/lib/gcc/x86_64-redhat-linux/4.4./../../../../include/c++/4.4./iostream:,
from ./main.cpp::
/usr/lib/gcc/x86_64-redhat-linux/4.4./../../../../include/c++/4.4./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./../../../../include/c++/4.4./bits/ios_base.h:: 错误:‘std::ios_base::ios_base(const std::ios_base&)’是私有的
/usr/lib/gcc/x86_64-redhat-linux/4.4./../../../../include/c++/4.4./iosfwd:: 错误:在此上下文中
/usr/lib/gcc/x86_64-redhat-linux/4.4./../../../../include/c++/4.4./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./../../../../include/c++/4.4./iosfwd:: 附注:在这里第一次需要生成的方法‘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:: 附注:在这里第一次需要生成的方法‘std::basic_ostream<char, std::char_traits<char> >::basic_ostream(const std::basic_ostream<char, std::char_traits<char> >&)’
./main.cpp:: 错误: 初始化‘void Print(std::ostream, std::string)’的实参
二、可执行代码:
/*******************************************************************************
* 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 ;
}
编译&执行成功。
三、总结:
这里不明白的是为什么传递流对象不行,而传递引用可以。而且g++的编译错误信息又看不太懂。只能记住以后需要用到流对象做参数,使用传引用了。