为什么朋友函数优先于运算符的成员函数<< [英] Why friend function is preferred to member function for operator<<

查看:121
本文介绍了为什么朋友函数优先于运算符的成员函数<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当打印一个对象时,一个朋友操作符<<用来。我们可以使用成员函数for operator<< ?

When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ?

class A {

public:
void operator<<(ostream& i) { i<<"Member function";}
friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;}
};


int main () {

   A a;
   A b;
   A c;
   cout<<a<<b<<c<<endl;
   a<<cout;
  return 0;
}

一点是,friend函数使我们能够像这样使用

One point is that friend function enable us to use it like this

cout<<a<<b<<c

其他原因?

推荐答案

不是二元运算符的成员函数,右侧的成员函数作为另一个参数传递,左侧始终为 * this

You have to use a free function and not a member function as for binary operators the left hand side is always *this for member functions with the right hand side being passed as the other parameter.

对于输出流操作符,左手边总是流对象,所以如果你流到一个标准类,而不是自己编写流你必须提供一个自由功能,而不是你的成员类。

For output stream operators the left hand side is always the stream object so if you are streaming to a standard class and not writing the stream yourself you have to provide a free function and not a member of your class.

虽然可以提供一个后向流操作符作为成员函数,并且流如下:

Although it would be possible to provide a backwards stream operator as a member function and stream out like this:

myObject >> std::cout;

不仅会违反一个非常强的库惯例,正如你所指出的,链接输出操作不会由于从左到右分组>> ,工作。

not only would you violate a very strong library convention, as you point out, chaining output operations would not work due to the left-to-right grouping of >>.

/ strong>正如其他人所说,虽然你必须使它成为一个自由函数,只需要一个朋友如果流函数不能实现类的'公共接口。

As others have noted, while you have to make it a free function it only needs to be a friend if the streaming function cannot be implemented in terms of the class' public interface.

这篇关于为什么朋友函数优先于运算符的成员函数&lt;&lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆