Reload operator Parsing

Source: Internet
Author: User

Heavy-duty operators are good young people, but we often write a lot of repeated code for heavy-duty operators. This is boring, but it is also necessary. The more you load, the greater the elasticity of your class. However, you cannot do whatever you want. Playing games always follow the corresponding rules, and the same is true for writing heavy-duty operators!
The following are the rules of the game to be followed:
• The unary operator can be a member function without parameters or a non-member function with a parameter.
• Binary operators can be member functions with one parameter or non-member functions with two parameters.
• Operator =, operator [], operator (), operator-> can only be defined as a member function.
• Operator-> must return a pointer or an object that can be used.
• When operator ++ and operator are reloaded, an int parameter is included to indicate the suffix, and no parameter is included to indicate the prefix.
• Except operator new and operator delete, at least one non-built-in data type must be included in the overloaded operator parameters.
• The overloaded operators should try to simulate the behavior of operators to build types internally.
After reading the rules of the game, we will Dispart the implementation and attention of each part.
Overload of operator Input and Output
Pay attention to the following key points for >>and <<:
① The IO operator must be a non-member function. If it is defined as a member function, the Operation habits of the IO operator are opposite to those of the normal one. How strange it is! Now, you may ask, How can I call private members in an object? Don't worry. Aren't we friends and friends? I/O operator overload functions are defined as class member functions. This problem is solved.
② During the input, we may encounter errors. At this time, the object to be restored is in the initial state. That is, what we look like before the input.
③ I think this is a good example of C ++ primer. We can reload the operators, which means we have a lot of free space. However, we should not forget the nature of the IO operator, do not over-format it, and minimize it.
After paying attention to several points, let's look at a complete IO operator implementation example:
# Include <iostream>
# Include <string>
Using namespace std;
 
Class MyClass {
Private:
String name;
Int id;
Int prefix;
Int value;
Public:
MyClass (){};
MyClass (string n, int a, int p, int nm): name (n), id (a), prefix (p), value (nm) {} // use the initialization list to initialize the member object
 
Friend ostream & operator <(ostream & stream, MyClass o); // when operators are defined as non-member functions, they must be defined as friends of the operation class.
Friend istream & operator> (istream & stream, MyClass & o );
};
 
Ostream & operator <(ostream & stream, MyClass o)
{
Stream <o. name <"";
Stream <"(" <o. id <")";
Stream <o. prefix <"-" <o. value <"\ n ";
 
Return stream;
}
 
Istream & operator> (istream & stream, MyClass & o)
{
Cout <"Enter name :";
Stream> o. name;
Cout <"Enter id :";
Stream> o. id;
Cout <"Enter prefix :";
Stream> o. prefix;
Cout <"Enter value :";
Stream> o. value;
Cout <endl;
 
Return stream;
}
 
Int main ()
{
MyClass;
Operator> (cin, a); // equivalent to operator> (cin,)
Cout <a; // equivalent to operator <(cout,)
Return 0;
}
In my opinion, many things are all in the air. After reading the code, you will know that this guy is used in this way, so that it is standard. Now we will introduce Arithmetic Operators and Relational operators.
Reload of Arithmetic Operators and Relational operators
Generally, Arithmetic Operators and Relational operators are defined as non-member functions.
① Arithmetic operators
Let's see how the code is implemented:
# Include <iostream>
# Include <string>
 
Using namespace std;
 
Class Point
{
Public:
Point (){};
Point (int x _, int y _): x (x _), y (y _){};
Point (const Point & p ){
This-> x = p. x;
This-> y = p. y;
};
 
~ Point (){};
 
Friend Point operator + (Point & p1, Point & p2); // Add two objects
Friend Point operator + (int value, Point & p1); // sum of object and value
 
Friend ostream & operator <(ostream & OS, Point & p1 );
Private:
Int x;
Int y;
};
 
Point operator + (Point & p1, Point & p2)
{
Point temp;
 
Temp. x = p1.x + p2.x;
Temp. y = p1.y + p2.y;
 
Return temp;
}
 
Point operator + (int value, Point & p1)
{
Point temp;
 
Temp. x = p1.x + value;
Temp. y = p1.y + value;
 
Return temp;
}
 
Ostream & operator <(ostream & OS, Point & p1)
{
OS <p1.x <"" <p1.y <endl;
Return OS;
}
 
Int main ()
{
Point p1 (1, 2 );
Point p2 (3, 4 );
 
Cout <p1 + p2;
Cout <5 + p1;
 
Return 0;
}
② Equal operator www.2cto.com
First, the two objects of the equal operator "=" contain the same data for comparison. Secondly, operator = is defined, and operator must also be defined! =.
Friend bool operator = (Point & p1, Point & p2 );
Friend bool operator! = (Point & p1, Point & p2 );
 
.......
 
Bool operator = (Point & p1, Point & p2)
{
Return (p1.x = p2.x) & (p1.y = p2.y );
}
 
Bool operator! = (Point & p1, Point & p2)
{
Return! (P1 = p2 );
}
Assign value operator
The value assignment operator has an emphasis point. That is, the value assignment must return a reference to * this. To be defined as a member function.
Point & operator = (const Point & p1 );
Point & operator ++ = (const Point & p1 );
 
.....
 
Point & Point: operator = (const Point & p1)
{
This-> x = p1.x;
This-> y = p1.y;
 
Return * this;
}
 
Point & Point: operator + = (const Point & p1)
{
This-> x + = p1.x;
This-> y + = p1.y;
 
Return * this;
}
Subscript operator
The container class that can retrieve a single element from the container generally defines the subscript operator []. First, you must note that the subscript operator must be defined as a member function. Second, two versions must be defined. One is a non-const member and a reference is returned. One is a const member and returns a reference.
# Include <iostream>
Using namespace std;
 
Class Point {
Int a [3];
Public:
Point (int I, int j, int k ){
A [0] = I;
A [1] = j;
A [2] = k;
}
Int & operator [] (int & I) {return * (a + I );}
Const int & operator [] (const int & I) {return * (a + I );}
 
};
 
Int main ()
{
Point ob (1, 2, 3 );
Cout <ob [1];
Return 0;
}
In sgi stl, we can see the reload situation: (concise enough)
Reference operator [] (size_type _ n) {return * (begin () + _ n );}
Const_reference operator [] (size_type _ n) const {return * (begin () + _ n );}
Member access operator
In C ++, The unreferenced operators (*) and arrow operators (->) are supported. The Arrow operators must be defined as class member functions. Take a look at the following usage:
_ Reference operator * () const {
_ BidirectionalIterator _ tmp = current;
Return * -- _ tmp; // return Value
}
 
Pointer operator-> () const {return & (operator * () ;}// return pointer
Auto-increment and auto-increment operations
A ++, ++ a, -- B, B --. Is it annoying? But after reading the meaning of heavy load, you will know that this is not annoying. I also know why the for loop must call ++.
In C ++, it is not particularly required to be a member function, but it is a good choice.
Note that:
① To be consistent with the built-in type, prefix operators should return the reference of the increment or decrement object;
② The suffix type returns the old value, which should be returned as a value, not a reference, so no reference is returned.
Now let's take a look at how to use it:
Point & operator ++ (); // to be consistent with the built-in type, the prefix operator should return the reference of the increment or decrement object
Point operator ++ (int); // returns the old value, which should be returned as a value instead of a reference.
 
Point & operator --();
Point operator -- (int );
....
// Pre-Increment
Point & Point: operator ++ ()
{
+ + This-> x;
+ + This-> y;
Return * this;
}
 
// Post-Increment
Point: operator ++ (int)
{
Point temp = * this;
+ + This-> x;
+ + This-> y;
Return temp;
}
 
// Minus
Point & Point: operator --()
{
-- This-> x;
-- This-> y;
Return * this;
}
 
// Subtraction
Point: operator -- (int)
{
Point temp = * this;
-- This-> x;
-- This-> y;
Return temp;
}
Do you know why I want to emphasize prefix? Look at the difference between the prefix and the suffix, and you will know that the efficiency will be high...
In summary, writing these things is a little hard, and the writing is stopped. Please tell me what's wrong. Thank you for your cooking...

From cloud flying elephant cg

Related Article

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.