C + + friend function makes binocular operator more humane

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.