Chapter 3 heavy-duty operators and transformations (3)

Source: Internet
Author: User

14.3 Arithmetic Operators and Relational operators
Generally, arithmetic and Relational operators are defined as non-member functions.
To be consistent with the built-in operators, addition returns a right value instead of a reference.

Friend Class1 operator + (const Class1 & c1, const Class1 & c2 );

Class1 operator + (const Class1 & c1, const Class1 & c2)
{
Class1 c (100 );
C. counter = c1.counter + c2.counter;
Return c;
}

Class1 c1 (200 );
Class1 c2 (300 );
Cout <c1 + c2 <endl;
A class that defines both Arithmetic Operators and Related Compound value assignment operators. Generally, compound values must be used to implement arithmetic operators.
14.3.1 equal Operators

Friend bool operator = (const Class1 & c1, const Class1 & c2 );

Inline bool operator = (const Class1 & c1, const Class1 & c2)
{
Return c1.counter = c2.counter;
}

Class1 c1 (200 );
Class1 c2 (300 );
Bool I = c1 = c2;
Cout <I <endl;
Classes with operator = defined are easier to use with the standard library. Some algorithms, such as find, use the = operator by default. If the class defines =, these algorithms can be used for this type without any special processing.
14.3.2 Relational operators
Use the default <operator to associate containers and some algorithms. Generally, Relational operators, such as equal operators, should be defined as non-member functions.

From xufei96's column

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.