Home>

C++ unary operator overloading

The unary 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 the method of overloading the binocular operator.But since the unary operator has only one operand,So operator overloaded functions have only one parameter,If an operator overloads a function as a member function,You can also omit this parameter.

The following uses the increment operator "++" as an example to introduce the overloading of the unary operator.

[Example] There is a time class, which contains data members minute (minute) and sec (second), analog stopwatch,One second at a time,60 minutes into one minute,At this point, the second counts from 0 again. Requires output of minutes and seconds.

#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 ++ ();//Declares operator overloaded functions
 void display () {cout<minute<<<>
 private:
 int minute;
 int sec;
};
time time ::operator ++ () //Define operator overloading function
{
 if (++ sec>= 60)
 {
  sec-=60;//1 minute for 60 seconds
  ++ minute;
 }
 return * this;//Return the current object value
}
int main ()
{
 time time1 (34,0);
 for (int i=0;i<61;i ++)
 {
  ++ time1;
  time1.display ();
 }
 return 0;
}

The operation is as follows:

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

You can see that the operator "++" is overloaded in the program,Make it available for time class objects. There are two ways to use the "++" and "-" operators.Pre-increment and post-increment operators.Their role is different,How to distinguish between the two during overloading?

In response to the characteristics of "++" and "-",C++ convention, in the overload function of the increment (decrement) operator,Adding an int parameter is the post-increment (decrement) operator function.

[Example] Add an overload to the post-increment operator based on the above example program.The modified procedure 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 ++ ();//Declares the pre-increment operator "++" overload function
 time operator ++ (int);//Declaration of post-increment operator "++" overload function
 void display () {cout<minute<<<":<<sec<<endl;}
 private:
 int minute;
 int sec;
};
time time ::operator ++ () ///Define the pre-increment operator "++" overload function
{
 if (++ sec>= 60)
 {
  sec-=60;
  ++ minute;
 }
 return * this;//Return the current object after adding
}
time time ::operator ++ (int) ///Define the post-increment operator "++" overload function
{
 time temp (* this);
 sec++;
 if (sec>= 60)
 {
  sec-=60;
  ++ minute;
 }
 return temp;//Returns the object before adding
}
int main ()
{
 time time1 (34,59), time2;
 cout<<"time1:";
 time1.display ();
 ++ time1;
 cout<""++ time1:";
 time1.display ();
 time2=time1 ++;//Assign the value of the object before adding to time2
 cout<"time1 ++:";
 time1.display ();
 cout<"time2:";
 time2.display ();//Output the value of time2 object
}

Please note the difference between the pre-increment operator "++" and the post-increment operator "++".The former is added first,What is returned is the modified object itself.The latter returns the object since the addition,The object is then incremented.Carefully analyze the post-increment operator overload function.

The results are as follows:

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

can be seen,When overloading the post-increment operator,One more int parameter,This parameter is added just to distinguish it from the pre-increment operator overload function,Also it has no effect.When the compilation system encounters an overloaded post-increment operator,This function is called automatically.

C++ binocular operator overloading

Binary operators (or binary operators) are the most commonly used operators in C++.Binary operators have two operands,Usually on the left and right sides of the operator,Such as 3 + 5, a=b, i<10 and so on. When overloading the binocular operator,It goes without saying that there should be two parameters in the function.

[Example] Define a string class string to store strings of indefinite length.The overloaded operators "==", "<", and ">" are used for comparison operations of equal, less than and greater than two strings.

To make it easier for the reader to understand the program,It also educates readers on the steps to build a program,Here are a few steps to introduce the programming process:

1) First create a string class:

#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 a string
};
string ::string (char * str) //Define the constructor
{p=str;} //Make p point to the argument string
void string ::display () //Output the string pointed to by p
{cout<p;}
int main ()
{
 string string1 ("hello"), string2 ("book");
 string1.display ();
 cout<endl;
 string2.display ();
 return 0;
}

The result is:

hello
book

2) With this foundation,Add other necessary content.Now add the operator overloading section.To facilitate writing and debugging,First overload 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);//Declares the operator function as a friend function
  void display ();
  private:
  char * p;//character pointer,Used to point to a string
};
string ::string (char * str)
{p=str;}
void string ::display () //Output the string pointed to by p
{cout<p;}
bool operator>(string&string1, string&string2) //Define operator overloading 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 running the program is 1.

This is just an incomplete program,However, the substantive work has been completed,Operator overloading succeeded.The overloads of the other two operators are just as well.

3) Expanded to overload 3 operators.

Declare 3 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 3 operator overload functions outside the class:

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

Modify the main function again:

int main ()
{
 string string1 ("hello"), string2 ("book"), string3 ("computer");
 cout<(string1>string2)<endl;//comparison result should be true
 cout<(string1<string3)<endl;//comparison result should be false
 cout<(string1 == string2)<endl;//The comparison result should be false
 return 0;
}

The result is:

1
0
0

The result is clearly correct.So far,The main tasks are basically completed.

4) further refinement,Make the output more intuitive.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 ::display () //Output the string pointed to by p
{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 ();cout<<">";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 result is:

hello>book
book<computer
hello == hello

Added a compare function to compare two strings.And output the corresponding information.This can reduce the burden on the main function,Make the main function concise and readable.

With this example,Not only can you learn about binocular operator overloading,You can also learn how to write C++ programs. Since the C++ program contains classes,Generally longer.Some readers who are new to C++ are embarrassed when they see longer programsI don't know how to proceed to read and analyze it.It's your turn to programNot knowing where to start, often without careful consideration,Write whatever you think,Wrote the program in one breath,As a result,There are so many mistakes that it takes a lot of time just to find the wrong position.Based on the experience of many beginners,The method introduced above is very suitable for beginners without programming experience.Enables people to design programs with clear ideas,Reduce the chance of error, Improve debugging efficiency.

The guiding idea of ​​this method is:first build the framework,Gradually expand,From simple to complex,Finally perfected.Programming, debugging, and expansion. Never try to address all the details in the first place.Classes are extensible,It can be expanded step by step.It is better to write the program directly on the computer,Each step must be commissioned on the machine,Debugging passed the previous step before doing the next step,Step by step.In this way, the efficiency of programming and debugging is relatively high.You can experiment.

c
  • Previous Batch processing to achieve chaotic rain (Matrix effects)
  • Next In-depth analysis of java HashMap implementation principle