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