读书人

请问重载lt;lt;的有关问题

发布时间: 2012-02-10 21:27:42 作者: rapoo

请教重载<<的问题
class LinearList
{
public:
std::ostream& operator < <(std::ostream& out,const LinearList <T> & t);
...
}

template <class T>
void LinearList <T> ::OutPut(ostream& out) const
{
for(int i = 0;i i <m_length;++i)
{
out < <m_element[i] < < " ";
}
}

template <class T>
ostream& operator < <(ostream& out,const LinearList <T> & t)
{

t.OutPut(out);
return out;
}

error C2804: binary 'operator < < ' has too many parameters
error C2804: binary 'operator < < ' has too many parameters
being compiled
with
[
T=int
]
error C2679: binary ' < < ' : no operator found which takes a right-hand operand of type 'LinearList <T> ' (or there is no acceptable conversion)
with
[
T=int
]



[解决办法]
class LinearList
{
public:
//应是全局的友元,而不是成员,如果是成员就会有一个隐藏的参数,自然说你参数太多.
friend std::ostream& operator < <(std::ostream& out,const LinearList <T> & t);
...
}
[解决办法]
重载运算符不能做为成员函数,因为运算符左操作数必须为ostream或者istream的引用,如果是成员函数,则左操作数就是当前class的this指针.

读书人网 >C++

热点推荐