Detail monocular operator overloading and binocular operator overloading in C++ programming

  • 2020-05-05 11:36:25
  • OfStack

C++ monocular operator overloads
The monocular operator has only one operand, such as! a, -b, &c, *p, and the most commonly used ++i and --i. Overloading a monocular operator is similar to overloading a binocular operator. But since the monocular operator has only one operand, the operator overload function has only one argument, which can also be omitted if the operator overload function is a member function.

Here is an example of overloading of the unary operator, using the self-increment operator "++".

There is an Time class, which contains the data members minute(minutes) and sec(seconds). It simulates a stopwatch, which walks for one second at a time, advances for one minute after 60 seconds, and then starts from 0 again. Requires the value of minutes and seconds to be output.


#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 an operator overload function 
 void display( ){cout<<minute<<":"<<sec<<endl;} // Define the output time function 
 private:
 int minute;
 int sec;
};
Time Time::operator++( ) // Defines an operator overload function 
{
 if(++sec>=60)
 {
  sec-=60; // full 60 Seconds into the 1 minutes 
  ++minute;
 }
 return *this; // Returns the current object value 
}
int main( )
{
 Time time1(34,0);
 for (int i=0;i<61;i++)
 {
  ++time1;
  time1.display( );
 }
 return 0;
}

Here's how it works:


34:1
34:2
 ┆ 
34:59
35:0
35:1 ( Total output 61 line )

As you can see, the operator "++" is overloaded in the program to make it available to Time class objects. The "++" and "--" operators are used in two ways, the pre - and post-increment operators and their functions are different. How to distinguish them when overloaded?

For "++" and "--" this characteristic, C++ convention, in the self-increment (self-decrement) operator overload function, add an int parameter, is the post self-increment (self-decrement) operator function.

Add an overloading of the postfix auto-increment operator to the above example program. The revised program is as follows:


#include <iostream>
using namespace std;
class Time
{
 public:
 Time( ){minute=0;sec=0;}
 Time(int m,int s):minute(m),sec(s){}
 Time operator++( );// Declare the pre - increment operator" ++ "Overloaded function 
 Time operator++(int);// Declare the postfix auto-increment operator" ++ "Overloaded function 
 void display( ){cout<<minute<<":"<<sec<<endl;}
 private:
 int minute;
 int sec;
};
Time Time::operator++( )// Define the preposition self-increment operator" ++ "Overloaded function 
{
 if(++sec>=60)
 {
  sec-=60;
  ++minute;
 }
 return *this;// Returns the current object since the append 
}
Time Time::operator++(int)// Define the postfix auto-increment operator" ++ "Overloaded function 
{
 Time temp(*this);
 sec++;
 if(sec>=60)
 {
  sec-=60;
  ++minute;
 }
 return temp; // Returns the self - superimposed object 
}
int main( )
{
 Time time1(34,59),time2;
 cout<<" time1 : ";
 time1.display( );
 ++time1;
 cout<<"++time1: ";
 time1.display( );
 time2=time1++; // Assigns the value of the preceding object to time2
 cout<<"time1++: ";
 time1.display( );
 cout<<" time2 :";
 time2.display( ); // The output time2 The value of the object 
}

Notice the difference between the pre - and post-increment operators "++" and "++". The former is self-added and returns the modified object itself. The latter returns the object before the autoincrement, and then the object autoincrement. Examine the postincrement operator overload function carefully.

The result is as follows:


time1 : 34:59(time1 The original cost )
++time1: 35:0 ( perform ++time1 after time1 The value of the )
time1++: 35:1 ( To perform time1++ after time1 The value of the )
time2 : 35:0 (time2 Save the execution time1++ before time1 The value of the )

As you can see, when the postfix auto-increment operator is overloaded, there is an int parameter, which is added only to distinguish it from the prefix auto-increment operator overload function, and has no effect whatsoever. The compiler automatically calls this function when it encounters an overloaded postfix auto-increment operator.

C++ binocular operator overloads
The binocular operator (or binary operator) is the most commonly used operator in C++. Binocular operators have two operands, usually on either side of the operator, such as 3+5, a=b, i< 10 and so on. When overloading a binocular operator, it goes without saying that there should be two arguments in the function.

Defines a string class String to hold strings of indefinite length, overloading the operators "==", "<" "And" > ", used to compare two strings equal, less than, and greater than.

To help the reader understand the program and the steps to creating it, here are a few steps:
1) first create an String class :


#include <iostream>
using namespace std;
class String
{
 public:
 String( ){p=NULL;} // Default constructor 
 String(char *str); // The constructor 
 void display( );
 private:
 char *p;// Character pointer , Used to point to strings 
};
String::String(char *str) // Define the constructor 
{p=str;} // make p Points to an argument string 
void String::display( ) // The output p The string that is pointed to 
{cout<<p;}
int main( )
{
 String string1("Hello"),string2("Book");
 string1.display( );
 cout<<endl;
 string2.display( );
 return 0;
}

The result is:


Hello
Book

2) after having this foundation, add other necessary contents. Now add the part that overloads the operator. To make it easier to write and debug, first override an operator "> ". 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);// Declare operator functions as friend functions 
  void display( );
  private:
  char *p;// Character pointer , Used to point to strings 
};
String::String(char *str)
{p=str;}
void String::display( ) // The output p The string that is pointed to 
{cout<<p;}
bool operator>(String &string1,String &string2)// Defines an operator overload 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 program runs to 1.

This is a very imperfect program, but the real work is done, and the operator overloading is successful. The other two operators can be overloaded in the same way.

3) extend to overloading 3 operators.
Declare three member functions in the 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 three operator overload functions outside the class:


bool operator>(String &string1,String &string2) // Pair operator" > "Overloading 
{
 if(strcmp(string1.p,string2.p)>0)
  return true;
 else
  return false;
}
bool operator<(String &string1,String &string2) // Pair operator" < "Overloading 
{
 if(strcmp(string1.p,string2.p)<0)
  return true;
 else
  return false;
}
bool operator==(String &string1,String &string2) // Pair operator" == "Overloading 
{
 if(strcmp(string1.p,string2.p)==0)
  return true;
 else
  return false;
}

Modify the main function:


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

The result is:


34:1
34:2
 ┆ 
34:59
35:0
35:1 ( Total output 61 line )
0


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

4) further modification to make the output more intuitive. Here is the final procedure.


34:1
34:2
 ┆ 
34:59
35:0
35:1 ( Total output 61 line )
1

The result is:


34:1
34:2
 ┆ 
34:59
35:0
35:1 ( Total output 61 line )
2

Added an compare function to compare two strings and output the corresponding information. This reduces the load on the main function and makes it simple to read.

With this example, you can learn not only about binocular operator overloading, but also how to write an C++ program. Because C ++ programs contain classes and are generally long, some novice C++ readers are intimidated by longer programs and don't know how to start reading and analyzing them. Turn to their own programming, more do not know where to hand, often without careful consideration, think of what to write what, one breath to write out the program, the results of a run, mistakes, just to find the wrong place to spend a lot of time. According to the experience of many beginners, the above method is very suitable for beginners without programming experience, can make people with a clear idea of programming, reduce the chance of error, improve debugging efficiency.

The guiding principle of this method is: first build the frame, gradually expand, from simple to complex, and finally perfect. Programming, debugging, expansion. Never attempt to resolve all the details at the outset. A class is extensible and its functionality can be expanded step by step. Had better write a program directly on the computer, every step should go up the machine debugging, debugging through the previous step to do the next step, step by step. This makes programming and debugging more efficient. You can try it out.


Related articles: