The magical of C + + operator overloading

Source: Internet
Author: User

Operator overloading (Operator overloading) is one of the important features of C + +, this article describes the use of operator overloading in the C + + standard library. If you have a handle on C + + operator overloading, you don't need to look down.

The advantage of operator overloading is that it makes the code concise. Here are a few examples of standard libraries that use operator overloading instead of code brevity.


Hello, World and operator<<

The first C + + program I saw when I learned C + + was Hello World, and it looked like this:

#include <iostream>using namespace Std;int main (int argc, char *argv[]) {cout << "Hello, world!" << Endl; return 0;}

At that time, I thought cout << sth and cin >> XXX This is "required format"; This is just an epitome of operator overloading in the standard library. The actual call here is the <string> definition:

  extern template ostream& operator<< (ostream&, const char*);


Containers and operator[]

The following shows examples of vectors and maps that make programs concise because they provide operator[].


Vector::operator[]

The Vector,map in the STL container (Container) provides operator[], and for vector,operator[] makes its usage "and array similar", that is, you can use subscript to access the elements of the vector:

Without operator overloading, the same functionality is likely to be written:

This is no longer as "kind" as the array.

The following code is the code that asks for all the elements within the vector<int> Ivec:

int sum = 0;for (int i=0; i < ivec.size (); i++) {sum + = Ivec[i];}


Map::operator[] Similar, operator[] makes the map very useful. For example, the core code for Word statistics using standard library map and string has only the following lines:
String word;map<string, Int> dict;while (cin >> word) {dict[word]++;//operator[]}

Can be seen from the cplusplus.com, for the map, if there is no operator[], the above dict[word]++ line to write:

Map<string, Int>::iterator it = dict.find (word); if (It! = Dict.end ()) {it->second++;} else {Dict.insert (Make_pair (Word, 1));}

Using the C + + standard library to implement the "word statistics", the entire program is as follows:

#include <cstdio> #include <iostream> #include <map> #include <string>using namespace Std;int Main (int argc, char *argv[]) {string word;map<string, int> dict;while (cin >> word) {dict[word]++;} Output:for (map<string, int>::iterator it = Dict.begin (); It! = Dict.end (); ++it) {cout << it->first <& Lt "\ t" << it->second << "\ n";} return 0;}
This program not only completes the word count, but also outputs it in the dictionary order of the words, all dependent on the operator overloads of the standard library.

Iterators and operator++

The above "Word statistics" code, has been used to design the iterator, is the "iterator." Simply put, an iterator is a class type with pointer functionality, and its pointer function is implemented by operator overloading.

For example, the following code can output all the elements of vecotr<int> Ivec:

for (Vector<int>::iterator it = Ivec.begin (); It! = Ivec.end ();//operator!=it++) {//operator++printf ("%d\n", *it) ; operator*}
This short code calls the three operator of the iterator overload. Operator overloading makes it possible to iterate around the for loop in the same way as the array.

The most radical thing about iterators is:


String and operator+=

The standard library string, which provides operator[], allows the user to access the characters in the string using the subscript operator, which is the same as the char array, char pointer. For example:

Str1[0] = str2[0];str2[0] = ' A ';

In addition to this, string provides an overloaded operator+= that appends characters and strings (including char Array,char pointer) to an existing string object. For example:

STR1 + = '! '; STR1 + = str2;str1 + = "literal string";


function object with operator ()

Of the many algorithms offered by <algorithm>, most of them have two versions, one of which has more than one parameter called function object, such as sort:

Template <class randomaccessiterator>  void sort (randomaccessiterator first, Randomaccessiterator last); Template <class Randomaccessiterator, class compare>  void Sort (randomaccessiterator first, Randomaccessiterator last, Compare comp);
Comp is called a function Object.

What exactly is a function object? A literal understanding is an object that can be called by a function, which is actually an object that overloads the operator (), for example, to sort an element by a string length on a vector<string>, and to pass in an instance of this functor:

struct Strlencomp{bool operator () (const string& A, const string& b) {return a.length () < B.length ();};
Of course, if you are familiar with c++11, this functor function object can be represented by a single line of lambda expressions:

[] (const string& A, const string& b) {return a.length () < B.length ();}


Summary

Listed above are examples of the most widely known operator overloads in the standard library, but the standard library uses operator overloading much more than that.


Essence

The operator overloads in C + + are actually no different from the member functions, just a little more concise. At compile time, they are both modified to the name inside the compiler, as well as "overloaded"--Different parameter lists.

The magic of C + + 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.