c++ - 为什么友元运算符<<在某些情况下使用而在其他情况下不使用

标签 c++ operator-overloading member

假设我有一个类 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/

相关文章:

c++ - 为什么 is_permutation 的最坏情况是 O(n^2)?

c++ - 编译器无法识别重载构造函数 C++

c++ - 当解引用运算符 (*) 被重载时,*this 的使用会受到影响吗?

C++模板静态成员实例化

C++回调系统。指向成员函数的指针

c++ - STL std::map 和 std::vector ;检查 map 中的对象类型

使用 future 、 promise 、分离线程时出现 C++ 错误 C2893、C2780、C2672

c++ - 重载类型转换运算符的语法

不同类型的 C++ 映射赋值重载

c++ - 是否可以使用未定义为 const 的工厂方法来定义 const 成员?