本例通过操作符重载、函数重载及函数指针等相关技术模拟实现C++输出流,具体代码如下:
//FileStream.h
// FileStream.h: interface for the CFileStream class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_FILESTREAM_H__38C31298_92F6_4273_B6CF_C9718B5B5D69__INCLUDED_)
#define AFX_FILESTREAM_H__38C31298_92F6_4273_B6CF_C9718B5B5D69__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <fstream.h>
class CFileStream
{
public:
CFileStream();
virtual ~CFileStream();
public:
bool Open(char const* const pchFileName); //打开文件
bool Close(void); //关闭文件
public:
CFileStream& operator<<(int nData);
CFileStream& operator<<(float fData);
CFileStream& operator<<(char chData);
CFileStream& operator<<(int (*Func)(const int &nData));
private:
ofstream m_OutFile;
};
#endif // !defined(AFX_FILESTREAM_H__38C31298_92F6_4273_B6CF_C9718B5B5D69__INCLUDED_)
//FileStream.cpp
// FileStream.cpp: implementation of the CFileStream class.
//
//////////////////////////////////////////////////////////////////////
#include "FileStream.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFileStream::CFileStream()
{
}
CFileStream::~CFileStream()
{
}
//打开文件
bool CFileStream::Open(char const* const pchFileName)
{
m_OutFile.open(pchFileName, ios::binary | ios::in, 0);
return true;
}
//关闭文件
bool CFileStream::Close()
{
m_OutFile.close();
return true;
}
CFileStream& CFileStream::operator<<(int nData)
{
m_OutFile<<nData<<endl;
return *this;
}
CFileStream& CFileStream::operator<<(float fData)
{
m_OutFile<<fData<<endl;
return *this;
}
CFileStream& CFileStream::operator<<(char chData)
{
m_OutFile<<chData<<endl;
return *this;
}
CFileStream& CFileStream::operator<<(int (*Func)(const int &nData))
{
m_OutFile<<Func;
return *this;
}
//main
#include "FileStream.h"
int Func(const int &nData)
{
return nData;
}
void main(void)
{
CFileStream file;
file.Open("C:\\tiger.txt");
file<<3<<4.5f<<'f';
file<<4<<6.78f<<'r';
file<<Func(100);
file.Close();
cout<<"文件写入完毕!"<<endl;
}