如果可能,作为非会员和非朋友功能。
正如 Herb Sutter 和 Scott Meyers 所描述的,与成员函数相比,更喜欢非朋友非成员函数,以帮助增加封装。
在某些情况下,例如 C++ 流,您没有选择权,必须使用非成员函数。
但是,这并不意味着你必须让这些函数成为你的类的朋友:这些函数仍然可以通过你的类访问器访问你的类。如果您以这种方式成功编写了这些函数,那么您就赢了。
关于运算符 << 和 >> 原型
我相信你在问题中给出的例子是错误的。例如;
ostream & operator<<(ostream &os) {
return os << paragraph;
}
我什至无法开始思考这种方法如何在流中工作。
以下是实现 << 和 >> 运算符的两种方法。
假设您想使用类型为 T 的类流对象。
并且您想从/插入到 T 中您的段落类型对象的相关数据。
通用运算符 << 和 >> 函数原型
第一个是作为函数:
// T << Paragraph
T & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// T >> Paragraph
T & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)
{
// do the extraction of p_oParagraph
return p_oInputStream ;
}
通用运算符 << 和 >> 方法原型
第二个是作为方法:
// T << Paragraph
T & T::operator << (const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return *this ;
}
// T >> Paragraph
T & T::operator >> (const Paragraph & p_oParagraph)
{
// do the extraction of p_oParagraph
return *this ;
}
请注意,要使用此表示法,您必须扩展 T 的类声明。对于 STL 对象,这是不可能的(您不应该修改它们......)。
如果 T 是 C++ 流呢?
以下是 C++ 流的相同 << 和 >> 运算符的原型。
对于通用 basic_istream 和 basic_ostream
请注意,这是流的情况,因为您不能修改 C++ 流,所以必须实现函数。这意味着类似:
// OUTPUT << Paragraph
template <typename charT, typename traits>
std::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// INPUT >> Paragraph
template <typename charT, typename traits>
std::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)
{
// do the extract of p_oParagraph
return p_oInputStream ;
}
对于 char istream 和 ostream
以下代码仅适用于基于字符的流。
// OUTPUT << A
std::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// INPUT >> A
std::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)
{
// do the extract of p_oParagraph
return p_oInputStream ;
}
Rhys Ulerich 评论说基于字符的代码只是它上面的通用代码的“专业化”。当然,Rhys 是对的:我不推荐使用基于 char 的示例。仅在此处给出它是因为它更易于阅读。因为它只有在你只使用基于字符的流时才可行,所以你应该避免在 wchar_t 代码很常见的平台上(即在 Windows 上)。
希望这会有所帮助。