For C + + friend functions, the most common scenario I have used in C + + programming for so many years is when you overload the binocular operator. Each time you define a new binocular operator, you will naturally think of it.
What are the benefits of using it?
No, what's going to happen?
Let's take a look at the situation, how to define a binocular operator.
Class mystring{public:mystring (char* s): M_data (NULL) {Delete M_data;m_data = new char[100];strcpy (m_data, s);} In the member function, overload operator MyString operator+ (const mystring& RHS) {MyString s (""); strcat (S.m_data, m_data); Strcat (S.m_data, Rhs.m_data); return s;} Private:char* m_data;};
Then, the result of the use is:
MyString s ("ABC"); MyString S1 = s + "abc"; okmystring s2 = "abc" + S; Error!!!
Because it is defined as a member variable of a class, you can only make implicit conversions of constructors in the second argument. Once the parameters are reversed, the error is immediately. So this method is not suitable for the description of natural language, the use of the limitations are large.
However, this problem can be solved well by means of the definition of friend function.
Class mystring{public:mystring (char* s): M_data (NULL) {Delete M_data;m_data = new char[100];strcpy (m_data, s);} Defined as friend function friend MyString operator+ (const mystring& s1, const mystring& s2);p rivate:char* m_data;}; MyString operator+ (const mystring& s1, const mystring& s2) {MyString s (""); strcat (S.m_data, S1.m_data); Strcat ( S.m_data, S2.m_data); return s;}
So, the two ways of the call are unimpeded!
MyString s ("ABC"); MyString S1 = s + "abc"; okmystring s2 = "abc" + S; Ok
C + + friend function makes binocular operator more humane