假设我有一个类 Complex
.
我都看过
friend ostream& operator<<( ostream& stream, Complex z)
(即友元函数)
ostream& operator<<( ostream& stream, Complex z)
(即成员函数)
使用过,我很难看清什么时候应该排除 friend ,什么时候包括 friend 被认为是重要的。
我的理解:成员函数和友元函数都可以访问类Complex
的私有(private)成员,友元函数只能在类本身中定义,它还可以访问其他类的私有(private)成员(也可以是公共(public)成员),而成员函数则不能。
另一个问题,因为ostream& operator<<( ostream& stream, Complex z)
是一个成员函数,为什么它不必在类本身中声明?我以为所有成员函数都必须在类中声明?
最佳答案
您可以通过两种方式实现运算符重载,如果您不需要通过隐式转换为 Complex
来调用它类型,你可以使用成员函数。 但是有缺点,通过免费功能提供,friend
如果需要访问私有(private)成员,则已成为标准方式。这里最好的引用是 Scott Meyer 关于如何 free functions improve encapsulation 的文章。 .他关于成员函数与非成员函数的建议明确包括 operator <<
:
if (f needs to be virtual) make f a member function of C; else if (f is operator>> or operator<<) { make f a non-member function; if (f needs access to non-public members of C) make f a friend of C; } else if (f needs type conversions on its left-most argument) { make f a non-member function; if (f needs access to non-public members of C) make f a friend of C; } else if (f can be implemented via C's public interface) make f a non-member function; else make f a member function of C;
关于c++ - 为什么友元运算符<<在某些情况下使用而在其他情况下不使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55217378/