Operator Overloading in C ++ Heavy Load Technology

Source: Internet
Author: User
Tags arithmetic operators bitwise operators

C ++The overload Technology in can be used not only for functions, but also for operators. Operator Overloading means that multiple meanings are given to existing operators, but the meanings of the same operator must be consistent. That is, addition operators cannot be used for subtraction, and so on.

Almost all operators can be overloaded, including Arithmetic Operators, bitwise operators, logical operators, comparison operators, and value assignment operators. Remember that these operators are not easy. We can remember that operators that cannot be overloaded include.",".*",": "And"? :".

Operator Overloading does not change the priority and combination of the original operator.

You can use member functions to overload operators, or you can use user Meta to overload operators.

Suppose we defineAnimalClass, and to output the object information, we can define an output function in the class in the form of friends, the definition is as follows:

Friend ostream & operator <(ostream & OS, animal & );

The preceding statement reloads the stream operator using the youyuan method. The first parameter in the function is a reference to the output stream, and the second parameter is a reference to the output object. The function returns a reference to the output stream, because the output is a reference of the output streamCout <A <B <C <Endl;.

If you change the function:

Friend out operator <(ostream & OS, animal & );

Therefore, continuous output of several objects cannot be achieved.

not only stream operators can be reloaded, but other operators can also be reloaded, take the simplest addition operator " + " as an example. The addition operator can implement many addition operations of built-in data types. If we define a class, such as animal class. To add the class objects, we need to implement" + " operator to add data members in the class.

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.