C + + Note (3): operator overloading

Source: Internet
Author: User
Tags arithmetic operators

Operator overloading

1. Operator Overloading Basics

2. Rules for operator overloading

3. Overloaded binocular operator

4. Overloaded single-mesh operators

5. Overloaded stream insertion and extraction operators

6. Type conversion

7. Define your own String class

--------------------------------------------------------------------------------------------------------------- ----------------

1. Operator Overloading Basics

Operator overloading is about giving new meaning to existing operators and implementing new functionality.
Earlier we have used operator overloading, such as "+", which can add operations to int, float, and string types. << is the left-shift operator in C + +, but in the output operation the cout mate is called the stream insertion operator, which can be output. >> is the right-shift operator, used in conjunction with CIN, which is called the stream extraction operator.
They are all called operator overloads.

We can also overload the existing operators in C + + based on our needs to give these operators new meanings. For example, the CTime class, overloaded with the + operator, implements the addition of two CTime objects.
Before introducing operator overloading, let's look at how to implement two CTime object additions.
The CTime overload + operator implements the addition of two CTime objects,
Time1 + time2

You first need to define an overloaded operator function, which is called automatically by the system when you execute the overloaded operator.

Operator overloading is actually an overload of a function .
Format of operator overloading
return type operator operator (argument list)
CTime operator+ (ctime& time1, ctime& time2)

Overloaded operator functions can be used as general functions or as member functions of a class.
CTime operator+ (ctime& time)

--------------------------------------------------------------------------------------------------------------- ----------------

2. Rules for operator overloading

The overloaded operator must be a C + + operator that already exists, and you cannot overload an operator that you create.
After the operator is overloaded, the original functionality is still preserved. Just extends the original functionality.
Overloading cannot change the number of operator operand objects. The + operator has two operands, and when the + operator function acts as a member function of the CTime, one of the arguments is implied, that is, the current object, using this to refer to. Another parameter is specified by the function parameter.
Operators that can be overloaded:
1. Arithmetic operators: +,-,*,/,%,
2. Logical operator: &&,| |,!
3. Relational operators: >,<,=,>=,<=,==,!=
4. Bitwise operator: ~,<<,>>,&,^), |
5. Self-increment decrement operator: ++,--
6. Compound assignment Operator: +=,-=,*=,/=,%=
7. Other:&, *, (),--, [],. New/delete, >>, <<

Operators that cannot be overloaded:?:. *:: sizeof
Operators that do not need to be overloaded:= (Assignment) and & (take address characters)
Assignment function
The normal function and the member function of the class can be the friend of the class, but when should use the normal function, when should use the member function way?
an operator function in the form of a normal function is generally declared as a friend function of a class to access the private data members of the class. this reduces overhead, but destroys encapsulation.

It is therefore recommended that you use member functions as much as possible.

The single-mesh operator is generally overloaded as a member function, and the binocular operator is overloaded as a friend function.
The member function requires the left argument to be the same as the class type.

The normal function requires that the argument order is the same as the order of the formal parameter type.
Such as
Some operators must be defined as member functions of a class: =, [], ()
Some operators cannot be defined as member functions of a class, but can only be defined as friends of a class:<<, >>
Operator overloading can perform arbitrary operations, such as the ability to subtract + from two objects, but this violates our daily habits, makes it easier to use misuse, and reduces program readability, so you must ensure that overloaded operators and the operator are applied to standard data types.

--------------------------------------------------------------------------------------------------------------- ----------------

3. Overloaded binocular operator

The so-called binocular operator is an operator with two operands. such as + 、-、 = = etc.
When you overload the binocular operator, you should have two parameters in the operator function, and if the operator function is a member function of the class, only one argument is required.
Instance
Overloading = =, >, < operators

--------------------------------------------------------------------------------------------------------------- ----------------

4. Overloaded single-mesh operators

The so-called Monocular operator is an operator with an operand. Such as! , + + 、--、 + =, etc.
When overloading a single-mesh operator, an operator function should have a parameter, and if the operator function is a member function of the class, there is no argument.
Instance
Overloaded + +, + = operators

--------------------------------------------------------------------------------------------------------------- ----------------

5. Overloaded stream insertion and extraction operators

The

Stream insert operator << and stream extraction operators >> can also be used to overload.
 
You can define overloaded stream insertions and stream extraction operators for the CTime class. The
overloads allow you to enter and output the CTime object directly:
Cout<<time;
cin>>time;
  In the previous section we introduced the rules for operator overloading,
<< and >> overloaded function declarations are as follows:
istream& operator>> (istream& input, ctime& Time);
ostream& operator<< (ostream& output, ctime& time);
istream and ostream are input stream classes and output stream classes respectively. cin and cout are objects of IStream and Ostream, respectively.
Functions for overloading >> stream extraction operators The first parameter and return type must be of type istream&.
Overloaded << stream insert operator The first parameter and return type must be ostream & type.


After overloading the stream insert and extract operators, we can use << output data for that class, and use >> to enter data. This is very intuitive.
cout<<time;
operator<< (cout, time);

cin>>time;
Operator>> (CIN, time);

--------------------------------------------------------------------------------------------------------------- ----------------

6. Type conversion

1. Using constructors for type conversions
After overloading the + operator for the CTime class, we can operate with the + operator on two CTime objects.
However, you cannot add an CTime object and an int type by using the + operator. To implement it, we can first convert the int type to a CTime temporary object, and then add it. As follows: Time + CTime (2)
CTime (2) This form is very similar to forcing a type conversion, converting an int type to a CTime type. This kind of conversion is possible because we have defined a constructor with an int type parameter for the CTime object. So a constructor with one parameter can be used to do a type conversion, called a transform constructor.
With the type conversion function, you can use the int type in place of the CTime type parameter.
2. type conversion function for type conversion
A type conversion function is used to convert an object of a class to a function of another data type. If you can convert an CTime class object to an int type.
int nsecond = time;
operator INT ()
No parameters, no return type.


--------------------------------------------------------------------------------------------------------------- ----------------

7. Define your own String class

The string class is convenient to use and we learned the string class at the beginning of the course.
So far, we've learned how to define classes and how to define operator overloading functions for classes.
Today we're going to define a string class of its own, similar to the string function.
constructor function:
String (const char *s); Initialize with C string s
String (int n,char c); Initialize with n characters c


Copy and assign values
string& String (string& str);
Const string& operator= (string& str);


Destructors
~string ();

Subscript Access:
Char &operator[] (int n);
char &at (int n) const;

The method provided by the String class:
int size () const; Returns the size of the current string
int length () const; Returns the length of the current string
BOOL empty () const; Whether the current string is empty

Overloaded stream insertion and extraction operators:
istream& operator>> (istream& input, string& str);
ostream& operator<< (ostream& output, string& str)

Connect two strings:
String &operator+= (string &s);
string comparison:
BOOL operator== (const string &s1,const string &s2) const;
int compare (const string &s) const;//Compare the size of the current string and s

--------------------------------------------------------------------------------------------------------------- ----------------

C + + Note (3): operator overloading

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.