The C ++ youyuan function makes binary operators more user-friendly.

Source: Internet
Author: User

The C ++ youyuan function makes binary operators more user-friendly.

For C ++ functions, I have used the most frequently used binary operators in C ++ programming over the years. Every time you define a new binary operator, you will naturally think of it.

What are the advantages of using it;

No, what will happen?

First, let's see how a binary operator is defined.

Class MyString {public: MyString (char * s): m_data (NULL) {delete m_data; m_data = new char [100]; strcpy (m_data, s );} // reload the 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 ;};
The result is:

MyString s ("ABC"); MyString s1 = s + "abc"; // OKMyString s2 = "abc" + s; // Error !!!
Because it is defined as a member variable of the class, only the second parameter can be implicitly converted to the constructor. Once the order of parameters is changed, an error is immediately reported. Therefore, this method is not suitable for the description of natural language, so it is very limited to use.

However, this problem can be well solved through the definition of the youyuan function.

Class MyString {public: MyString (char * s): m_data (NULL) {delete m_data; m_data = new char [100]; strcpy (m_data, s );} // It is defined as friend MyString operator + (const MyString & s1, const MyString & s2); private: 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 ;}
Then, the two methods of calling are unobstructed!

MyString s("ABC");        MyString s1 = s + "abc"; // OKMyString s2 = "abc" + s; // OK

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.