运算符<<重载c ++ [英] operator << overload c++
问题描述
如何重载<<运算符(for cout)所以我可以对类k做cout
类型 T
是这样的:
std :: ostream& operator<<<(std :: ostream& os,const T& obj)
{
os< obj.get_data1()<< get_data2();
return os;
}
注意,输出流操作符通常不是成员函数。 (这是因为二进制运算符是成员函数,他们必须是它们左边参数类型的成员,这是一个流,但是,而不是你自己的类型有一些重载对于一些内建函数,它们是输出流类的成员) $
因此,如果不是 T的所有数据
可公开访问,此操作员必须是 T
class T {
friend std :: ostream& operator<<(std :: ostream& const T&);
// ...
};
或者操作员调用一个公共函数进行流传输:
class T {
public:
void write_to_stream(std :: ostream&);
// ...
};
std :: ostream& operator<<<(std :: ostream& os,const T& obj)
{
obj.write_to_stream(os);
return os;
}
后者的优点是 write_to_stream )
成员函数可以是 virtual
(和pure),允许流式传输多态类。
如果你想成为和支持各种流,你必须模板化:
template<类型名TCh,类型名TTr>
std :: basic_ostream< TCh,TTr>&运算符<<<(std :: basic_ostream< TCh,TTr>& os,const T& obj)
{
os& obj.get_data1()<< get_data2();
return os;
}
(但是,模板不适用于虚拟函数。 p>
how can i overload "<<" operator (for cout) so i could do "cout" to a class k
The canonical implementation of the output operator for any type T
is this:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
os << obj.get_data1() << get_data2();
return os;
}
Note that output stream operators commonly are not member functions. (That's because for binary operators to be member functions they have to be members of their left-hand argument's type. That's a stream, however, and not your own type. There is the exception of a few overloads of operator<<()
for some built-ins, which are members of the output stream class.)
Therefor, if not all data of T
is publicly accessible, this operator has to be a friend of T
class T {
friend std::ostream& operator<<(std::ostream&, const T&);
// ...
};
or the operator calls a public function which does the streaming:
class T {
public:
void write_to_stream(std::ostream&);
// ...
};
std::ostream& operator<<(std::ostream& os, const T& obj)
{
obj.write_to_stream(os);
return os;
}
The advantage of the latter is that the write_to_stream()
member function can be virtual
(and pure), allowing polymorphic classes to be streamed.
If you want to be fancy and support all kinds of streams, you'd have to templatize that:
template< typename TCh, typename TTr >
std::basic_ostream<TCh,TTr>& operator<<(std::basic_ostream<TCh,TTr>& os, const T& obj)
{
os << obj.get_data1() << get_data2();
return os;
}
(Templates, however, don't work with virtual functions.)
这篇关于运算符<<重载c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!