读书人

成员函数operator lt;lt;调用endl的有关问

发布时间: 2012-02-19 19:43:39 作者: rapoo

成员函数operator <<调用endl的问题

class A
{ template <typename T> A& operator < <(const T t);
.....

private:

ofstream fout;
.........
};

template <typename T> A& A::operator < <(const T t)
{fout < <t;
fout.flush();
return *this;}
int main()
{A a;
a < < "1234\n " < <456 < < "\n "; //运行正确
......

return 0;}

把a < < "1234\n " < <456 < < "\n ";语句 改成 a < < "1234\n " < <456 < <endl编译就有误,我想使 < <操作符也能调用endl,请问成员函数operator < <应该怎么定义?



[解决办法]
endl 是在std名字空间中定义的,
#include <iostream>
using std::endl;
你就可以使用了,但是这样感觉不太舒服。

你可以自己定义一个宏,大致是
#define fout < <endl \
fout < < "\n ";\
fout.flush();
大概就是换行,刷新流。实际上做起来肯定比这要复杂一些,但也不会很麻烦。
[解决办法]
endl是个基于basic_ostream的较复杂的模板函数,从你的那个
template <typename T> A& A::operator < <(const T t)
根本无法推导出其所需的模板类型,解决办法可以是增加一个针对ostream的类似endl原型参数的operator < <,这样endl就能完成它所需的参数推导了。

#include <fstream>
using namespacestd;

class A
{
public:
A();
~A();
template <typename T>
A& operator < <(const T&t);

A& operator < <(ostream&(*pFunc)(ostream&));

private:
ofstream fout;
};

A::A() {
fout.open( "C:\\a.txt ");
}
A::~A(){
fout.close();
}

template <typename T>
A& A::operator < <(constT& t)
{
fout < <t;
fout.flush();
return *this;
}

A& A::operator < < (ostream&(*pFunc)(ostream&)){
pFunc(fout);
return *this;
}

intmain()
{
A a;
a < < "Hello World " < < endl;
return 0;
}

读书人网 >C++

热点推荐