C + + operator overloading

Source: Internet
Author: User

One, operator overloading:

Operator overloading is a polymorphic type that extends the functionality of operators so that operators are not only used for built-in data types.

Ii. rules for operator overloading:

  1.c++ does not allow users to define new operators themselves, only the existing C + + operators can be overloaded;

2. Overloading cannot change the number of operator operands (that is, shoving count), and cannot have default parameters, otherwise it also changes the number of operands, for example: "+" operator overload or only binocular operator;

3. Overloading does not change the precedence and associativity of operators;

4. Overloaded operators must be used with objects of a user-defined custom type, with at least one parameter that is a class object (or a reference to a class object);

5. Operators for class objects must generally be overloaded, but with two exceptions, operators "=" and "&" do not have to be overloaded;

6. The function of the overloaded operator should be similar to the function that the operator implements when it acts on a standard type of data;

7. An operator overload function can be a member function of a class, a friend function of a class, a non-class member function, or a common function of a friend function.

There are two ways to implement operator overloading:

1.friend function:

class class Name: {public:    operatoroperator  operator (formal parameter list) {     // definition }
View Code

2. Class member functions:

class class Name {public:    operator  operator (formal parameter list);}; return type class Name::operator  operator (formal parameter list) {    // definition }
View Code

Iv. overloads of different operators:

1.

C + + operator overloading

Related Article

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.