The single-eye operator overload and the binocular operator overload _c Language in C + + programming

Source: Internet
Author: User
Tags strcmp

C + + single-eye operator overloading
The monocular operator has only one operand, such as!a,-b,&c,*p, and the most commonly used ++i and-I. The method of overloading the monocular operator is similar to that of overloaded binocular operators. However, because the monocular operator has only one operand, the operator overload function has only one argument and can be omitted if the operator overloaded function acts as a member function.

The following is an example of the self-increasing operator "+ +", which describes the overloads of the monocular operator.

[Example] There is a time class that contains data members minute (minutes) and sec (seconds), analog stopwatch, one second each walk, full 60 seconds into a minute, and seconds starting from 0. The value of the output minute and second is required.

#include <iostream>
using namespace std;
Class time
{public
 : Time
 () {minute=0;sec=0;}//default constructor time
 (int m,int s): Minute (m), SEC (s) {}//constructor overload Time
 operator++ ();//Declare operator overloaded function
 void display () {cout<<minute<< ":" <<sec<<endl;} Define output Time function
 private:
 int minute;
 int sec;
Time time::operator++ ()///define operator overloaded function
{
 if (++sec>=60)
 {
  sec-=60;/full 60 seconds into 1 minutes
  ++minute;
 }
 return *this;//back to current object value
}
int main ()
{time
 time1 (34,0);
 for (int i=0;i<61;i++)
 {
  ++time1;
  Time1.display ();
 }
 return 0;
}

The operating conditions are as follows:

34:1
34:2
┆
34:59
35:0
35:1 (total output 61 lines)

You can see that the operator "+ +" is overloaded in the program so that it can be used with the time class object. There are two ways in which the "+ +" and "--" operators are used, the front and rear self-add operators are different, and how do you distinguish between them when overloading?

For the "+ +" and "--" this feature, the C + + convention, in the self-increment (self-subtraction) operator overloaded functions, add an int parameter, is the back of the self-increment (self-subtraction) operator function.

[Example] adds an overload to the back-up operator based on the above example program. The revised procedure is as follows:

 #include <iostream> using namespace std; class Time {Public:time () {Minute=0;se
 c=0;} Time (int m,int s): Minute (m), SEC (s) {} time operator++ ();//Declaration of pre-add operator "+ +" overloaded function time operator++ (int);//Declaration of post-increment operator "+ +" overloaded function V
 OID display () {cout<<minute<< ":" <<sec<<endl;}
 Private:int minute;
int sec;
};
  Time time::operator++ ()//defines the pre-add operator "+ +" overloaded function {if (++sec>=60) {sec-=60;
 ++minute;
 Return *this;//Returns the current object {time time::operator++ (int)/is defined after the add-in operator "+ +" overloaded function {Time temp (*this);
 sec++;
  if (sec>=60) {sec-=60;
 ++minute; return to temp;
 Returns the object before it is added {main () {time time1 (34,59), time2;
 cout<< "time1:";
 Time1.display ();
 ++time1;
 cout<< "++time1:";
 Time1.display (); time2=time1++;
 Assigns the value of the object before the addition to Time2 cout<< "time1++:";
 Time1.display ();
 cout<< "time2:"; Time2.display (); Output the value of the Time2 object} 

Note the difference between the preceding self-increasing operator "+ +" and the "+ +" operator "+ +". The former is the first to add, return is the modified object itself. The latter returns the object before it is added, and then the object is added by itself. Carefully analyze the post-add operator overload function.

The results of the operation are as follows:

time1:34:59 (time1 original value)
++time1:35:0 (time1 after ++time1)
time1++: 35:1 (time1++ after time1)
time2:35:0 ( Time2 saves the value of the time1 before executing time1++)

As you can see, when you overload the self-add operator, you have an int parameter, which is added only to make a difference to the overloaded function of the predecessor operator, and it has no effect. This function is called automatically when the compilation system encounters an overloaded, post-increment operator.

C + + binocular operator overloading
The binocular operator (or the two-dollar operator) is the most commonly used operator in C + +. The binocular operator has two operands, usually on the left and right sides of the operator, such as 3+5,a=b,i<10. When overloading a binocular operator, it is self-evident that there should be two parameters in the function.

[Example] defines a string class string that holds indefinite strings, overloaded operators "= =", "<", and ">" For comparison operations that are equal to, less than, and greater than two strings.

In order for readers to understand the program and also to make the reader aware of the steps to establish a program, the following step-by-step describes the programming process:
1 Create a String class first:

#include <iostream>
using namespace std;
Class String
{public
 :
 string () {p=null;}//default constructor
 string (char *str);//constructor
 void display ();
 Private:
 Char *p;//character pointer, used to point to string
};
String::string (char *str)//define constructor
{P=STR}//P to point to argument string void string
::d isplay ()//output p to the string
{cout <<p;}
int main ()
{
 String string1 ("Hello"), string2 ("book");
 String1.display ();
 cout<<endl;
 String2.display ();
 return 0;
}

The results of the operation are:

Hello Book

2 with this foundation, add other necessary content. Now increase the portion of the operator overload. For ease of writing and debugging, overload an Operator ">" first. The procedure is as follows:

#include <iostream>
#include <string>
using namespace std;
Class string
{public
  :
  string () {p=null;}
  String (char *str);
  friend bool Operator> (String &string1,string &string2);//Declaration operator function is friend function
  void display ();
  Private:
  Char *p;//character pointer, used to point to string
};
String::string (char *str)
{p=str;}
void string::d isplay ()//output P is pointing to the string
{cout<<p;}
BOOL Operator> (String &string1,string &string2)//define operator overloaded function
{
  if (strcmp (STRING1.P,STRING2.P) >0) return
   true;
  else return false;
int main ()
{
  String string1 ("Hello"), string2 ("book");
  cout<< (string1>string2) <<endl;
}

The result of the program running is 1.

This is just a not-so-perfect program, but the actual work has been done, and the operator overload has succeeded. The overloads of the other two operators do the same.

3) extended to 3 operator overloads.
Declare 3 member functions in a string class body:

 friend bool Operator> (string &string1, String &string2);
 friend bool operator< (string &string1, String &string2);
 friend bool operator== (String &string1, string& string2);

Define 3 operator overloaded functions outside of the class separately:

BOOL Operator> (String &string1,string &string2)//pair Operator ">" overload
{
 if (strcmp (STRING1.P,STRING2.P) >0) return
  true;
 else return
  false;
BOOL operator< (String &string1,string &string2)//pair operator "<" overload
{
 if (strcmp string1.p, STRING2.P) <0) return
  true;
 else return
  false;
BOOL operator== (String &string1,string &string2)//Operator ' = = ' overload
{
 if (strcmp (string1.p,string2.p) = = 0) return
  true;
 else return
  false;

And then modify the main function:

int main ()
{
 String string1 ("Hello"), string2 ("book"), String3 ("Computer");
 cout<< (string1>string2) <<endl; The comparison should be true
 cout<< (string1<string3) <<endl;//The comparison should result in false
 cout<< (string1== string2) <<endl; The comparison should result in false return
 0;

The results of the operation are:

1
0
0


The result is clearly right. So far, the main task is basically completed.

4) Further modification, so that the output more intuitive results. The final procedure is given below.

#include <iostream> using namespace std;
 Class String {public:string () {p=null;}
 String (char *str);
 friend bool Operator> (string &string1, string &string2);
 friend bool operator< (string &string1, string &string2);
 friend bool operator== (string &string1, string &string2);
 void display ();
Private:char *p;
}; String::string (char *str) {p=str} void string::d isplay ()//output P is pointing to the strings {cout<<p;} bool Operator> (String &
 string1, String &string2) {if (strcmp (STRING1.P, STRING2.P) >0) return true;
else return false;
 BOOL operator< (String &string1, String &string2) {if (strcmp (STRING1.P, STRING2.P) <0) return true;
else return false;
 BOOL operator== (String &string1, String &string2) {if (strcmp (STRING1.P, STRING2.P) ==0) return true;
else return false; } void Compare (String &string1, String &string2) {if (operator> (string1, string2) ==1) {string1.display (); Co ut<< ">";String2.display ();}
  else if (operator< (string1, string2) ==1) {string1.display ();cout<< "<"; String2.display ();}
 else if (operator== (string1, string2) ==1) {string1.display ();cout<< "="; String2.display ();}
cout<<endl;
 int main () {String string1 ("Hello"), string2 ("book"), String3 ("Computer"), String4 ("Hello");
 Compare (string1, string2);
 Compare (string2, string3);
 Compare (string1, string4);
return 0;
 }

The results of the operation are:

Hello>book
book<computer
Hello==hello

Added a compare function to compare two strings and output the appropriate information. This reduces the burden of the main function and makes the main function concise and readable.

In this example, not only can learn about the binocular operator overload knowledge, but also can learn how to write C + + programs. Because C + + program contains classes, generally relatively long, some beginners C + + readers see a longer program on the fear, do not know how to proceed to read and analyze it. Turn to their own programming, not knowing where to start, often without deliberate, think of what to write, a breath of the program written out, the results of a run, error-ridden, the light to find the wrong location to spend a lot of time. According to many beginners ' experience, the method described above is very suitable for beginners who have no programming experience, can make people design with clear ideas, reduce the chance of error and improve the efficiency of debugging.

The guiding ideology of this method is: first frame, gradually expand, from simple to complex, and finally perfect. Edge programming, side debugging, edge expansion. Never try to solve all the details at the beginning. The class is extensible and can be expanded step-by-step to extend its functionality. It is best to write the program directly on the computer, each step must be on the machine debugging, debugging through the previous step before doing the next steps. In this way, the efficiency of programming and debugging is relatively high. We can experiment.

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.