#include <iostream>
#include <fstream>
using namespace std;
class test
{
private:
int a;
public:
test(int c=0){a=c;}
friend ostream &operator<<(ostream &os,test &t);
friend ofstream &operator<<(ofstream &of,test &t);
};
ostream &operator<<(ostream &os,test &t)
{
os << "a=" << t.a;
return os;
}
ofstream &operator<<(ofstream &of,test &t)
{
of << "a=" << t.a;
cout << endl << "haha!";
return of;
}
int main()
{
ofstream fout;
test t1(1);
fout.open("test.txt");
cout << t1;
fout << t1; //如果这里写fout << "haha" << t1;编译器会把fout当做ostream对象来处理
//从而调用第一个函数;而fout << t1;会调用第二个函数,为什么?
fout.close();
return 0;
}
fout << "haha" <<t1调用第一个函数时,一样可以把内容写进文件里。
刚试了一下,如果不定义第二个函数的话也是可以通过编译的。
谢谢你