流操作符

版权声明:本文为博主原创文章,转载请保留原文链接。联系邮箱:[email protected] https://blog.csdn.net/Liwuqingxin/article/details/51065872

一、继承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;
	}
};

二、重载自定义类的<<

下面代码参考自:[]http://www.cnblogs.com/xkfz007/articles/2534322.html]

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;
};


猜你喜欢

转载自blog.csdn.net/Liwuqingxin/article/details/51065872