The combination of the C ++ operator and the operator

Source: Internet
Author: User

The combination of the C ++ operator and the operator

Operator overloading is one of the important features of C ++. This article introduces the usage of Operator overloading in the C ++ standard library. If you can easily master the operators of C ++, you do not need to continue reading them.

The benefit of Operator Overloading is-to make the code concise. The following describes some instances of the standard library that are concise in code due to the use of operator overloading.


Hello, World and operator <

When I first learned C ++, the first C ++ program was Hello World, which looked like this at the time:

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

At that time, I thought cout <something and cin> xxx was a "required format". This was just a microcosm of Operator Overloading in the standard library. What is actually called here is defined by <string>:

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


Container and operator []

The following example shows how vector and map simplify the program by providing operator.


Vector: operator []

The vector and map in the STL Container (Container) provide operator []. For vector and operator [], operator [] makes its usage "similar to array ", it is the element that can access the vector with Subscript:

int firstInt = ivec[0]; // operator[]ivec[0] = 1; // 

If there is no operator overload, the same function is likely to be written:

int firstInt = ivec.get(0); ivec.set(0, 1); 

This is no longer as "friendly" as an array.

The following code calculates all elements and codes in vector <int> ivec:

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


Map: operator [] is similar. operator [] Makes map very useful. For example, the core code for word statistics using the standard library map and string is as follows:
string word;map<string, int> dict;while(cin >> word){dict[word]++; // operator[]}

We can see from cplusplus.com that for map, if there is no operator [], the dict [word] ++ line above should be written:

map<string, int>::iterator it = dict.find(word);if(it != dict.end()) {it->second++;}else {dict.insert(make_pair(word, 1));}

The "word Statistics" implemented using the C ++ standard library 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 << "\t" << it->second << "\n";}return 0;}
This program not only completes "word Statistics", but also outputs words in alphabetical order, all dependent on the operator overloading of the standard library.

Iterator and operator ++

The above "word Statistics" code has been used to design iterator, which is exactly the "iterator ". In short, an iterator is a class type with a pointer function, and its "Pointer" function is implemented through Operator overloading.

For example, the following code outputs 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 three operators that are reloaded by iterator. Operator Overloading makes the for loop Writing Method and array iteration method similar here.

The most radical thing about the iterator is:

copy(istream_iterator<char>(cin), istream_iterator<char>(), ostream_iterator<char>(cout, "")); 


String and operator + =

The string in the Standard Library provides operator [] so that you can use the subscript operator to access characters in the string, which is the same as char array and char pointer. For example:

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

In addition, string also provides operator + = with heavy loads to append characters and strings (including char array and char pointer) to existing string objects ). For example:

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


Function object and operator ()

Most of the algorithms provided by <algorithm> have two versions. One version has an additional 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 is a Function Object? Literally, an object that can be called as a function is actually an object with operator () reloaded. For example, to sort the elements of a vector <string> by string length, you can input 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 Function Object of Functor can be expressed in a lambda expression line:

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


Summary

The above lists the most widely recognized examples of Operator Overloading in the standard library, but the place where the standard library uses Operator Overloading is far more than that.


Essence

In C ++, Operator Overloading is actually no different from member functions, but it is simpler to write. During compilation, they are all changed to the internal name of the compiler, and the "overload"-different parameter lists are also supported.


C/C ++ Operator Overloading

This value is a Hidden Pointer of the class. What does it mean? That is to say, we do not write this pointer when defining classes, but such a pointer is automatically generated, which points to the object itself.

Therefore, * this is to dereference the pointer, which is equivalent to the object of the class itself.

If Clock;
* This is actually similar to.

& Indicates a reference. In this form, the object of the class is returned and no temporary variables are created.
And can be used as the left value.

The left value is placed on the left of = and assigned to it with other values.

 
Why does C ++ need to use Operator Overloading? I think it's a little redundant.

There is no difference in the running result between operator overloading.
It is mainly convenient for users of class libraries. comparison class objects support addition operations. If you write a function, it looks better to use a +.

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.