Loading

C++中流操作符<<重载的实现

一、继承fstream后重载其<<

注意:重载函数中不能直接使用参数中的流out,否则会出现递归出错。

class CLogStream : public ofstream
{
public:
	string m_path = "ClogStream.log";
	CLogStream()
	{
		this->open(m_path, ios::app);
		if (this->is_open())
		{
			cout << "success!" << endl;
		}
	}

	friend CLogStream& operator<<(CLogStream& out, const char* str)
	{
		char* s = "CLogStream:";
		ofstream *ofs = &out;
		*ofs << s << str << endl;;
		return out;
	}
};

二、重载自定义类的<<

下面代码参考自这里

template<class T>
class Test// : public ofstream
{
public:
	Test(const T& t) :data(t){}
	//---------------------------------------------
	friend ostream& operator<<(ostream& out, Test<T>& t)    //输出流重载声明及实现
	{
		return out << "data   is   " << t.data;
	} //--------------------------------------------

	friend istream& operator>>(istream& in, Test<T>& t)      //输入流重载声明及实现
	{
		return in >> t.data;
	}//---------------------------------------------

	T data;
};
posted @ 2016-04-05 16:35  NLNet  阅读(83)  评论(0编辑  收藏  举报