C + + Learning notes-operator overloading

Source: Internet
Author: User
Tags diff

Operator overloading (operator overloading) is a form of C + + polymorphism in which C + + extends operator overloading to user-defined types, such as allowing the addition of two custom objects using +, which the compiler will use to determine the number and type of operands.

To overload an operator, you use the operator function, which is in the following format:

Operator OP (argument-list)

OP: the operator to overload

Argument-list: Operand

The operator function can be a member function of a class, or it can be a friend function, and if it is a class member function, the first operand is the calling object, which is not in argument-list.

Operator overloading example, defining a time class, Overload +-* operator.

Time.h

#ifndef Time_h_#defineTime_h_#include<iostream>classtime{ Public: Time (void); Time (intHintm =0); ~time (void); voidAddmin (intm); voidADDHR (inth); voidReset (inth =0,intm =0); voidShow ()Const; //overloaded + operatorTimeoperator+ (ConstTime & T)Const; timeoperator- (ConstTime & T)Const; // *Timeoperator* (DoubleNConst; //friend functionFriend timeoperator* (DoubleNConstTime &t); //Overloading << OperatorsFriend Std::ostream &operator<< (Std::ostream & OS,ConstTime &t);Private:    intm_hours; intm_minutes;};#endif

Concrete implementation of Time.cpp

1#include"Time.h"2 3 4Time::time (void)5: M_hours (0)6, M_minutes (0)7 {8 }9 TenTime::time (intHintm) One : M_hours (h) A , M_minutes (m) - { - } the  -  -Time::~time (void) - { + } -  + voidTime:: Addmin (intm) A { atM_minutes + =m; -M_hours + = m_minutes/ -; -M_minutes = m_minutes% -; - } - voidTIME::ADDHR (inth) - { inM_hours + =h; - } to voidTime::reset (intHintm) + { -M_hours =h; theM_minutes =m; * } $ voidTime::show ()ConstPanax Notoginseng { -Std::cout << m_hours <<":"<<m_minutes; the } +Time::operator+ (ConstTime & T)Const A { the Time sum; +Sum.m_minutes = M_minutes +t.m_minutes; -Sum.m_hours = m_hours + t.m_hours + sum.m_minutes/ -; $Sum.m_minutes = sum.m_minutes% -; $     returnsum; - } -Time::operator- (ConstTime & T)Const the { - Time diff;Wuyi     intTotal1,total2; theTotal1 = m_minutes + m_hours * -; -Total2 = t.m_minutes + t.m_hours * -; WuDiff.m_hours = (total1-total2)/ -; -Diff.m_minutes = (total1-total2)% -; About     returndiff; $ } -Time::operator* (DoubleNConst - { - Time result; A     LongTotal_minutes = m_hours * -* N + m_minutes *N; +Result.m_hours = total_minutes/ -; theResult.m_minutes = total_minutes% -; -     returnresult; $ } the  theTimeoperator* (DoubleNConstTime &t) the { the Time result; -     LongTotal_minutes = t.m_hours * -* N + t.m_minutes *N; inResult.m_hours = total_minutes/ -; theResult.m_minutes = total_minutes% -; the     returnresult; About } the  theStd::ostream &operator<< (Std::ostream & OS,ConstTime &t) the { +OS << t.m_hours <<":"<<t.m_minutes; -     returnos; the}
View Code
Time operator-(const time & T) const;
Overloaded subtraction operator, you can easily subtract the time object
Time Start_time (10,40);
Time End_time (11,50);

Time Diff_time = End_time-start_time;
when an operator function is a member function, the object to the left of the operator is the calling object, and the right-hand object is passed as a parameter, as the subtraction operation above is actually equivalent to:
end_time.operator-(start_time);

about operator Overloading:
1. Overload limit
1) The overloaded operator must have at least one operand to be a custom type, primarily to prevent the user from overloading the operator for the standard type.
2) The use of operators cannot violate the original syntactic rules of the operator. If% is a two-dollar operator, two operands are required and cannot be overloaded to use one operand.
3) The precedence of the operator cannot be modified
4) Unable to define new operator
5) The following operators cannot be overloaded:
sizeof
.
. *--member pointer operator
::
?:---conditional operator
typeID--a rtti operator
const_cast--Coercion type conversion character
dynamic_cast
reinterpret_cast
static_cast
6) Most operators can be overloaded with member functions or non-member functions, but the following operators are overloaded only by member functions:
= assignment operator
() function call operator
[] subscript operator
operator to access class members through pointers

2. Through friend function overloading
for many operators, you can choose to use member functions or non-member functions to implement operator overloading. In general, non-member functions should be friend functions, so that the private data of the class can be accessed directly.
such as for the addition operator of the time class:

using class member function overloading
Time operator+ (const time & T) const;

use non-member function overloading:
friend time operator+ (const time & T1, const time & T2);

for member function versions, an operand is implicitly passed through the this pointer, one through the parameter table
A friend version, two operands are passed as parameters
Both of these overloads can match T1+t2
However, in overloaded operators, only one of these formats can be selected, and the definition is treated as a ambiguity error, resulting in a compilation error.

In some cases, you must use friend to reload
in the time class, the multiplication operator differs from the other two overloaded operators by using two different types, combining a time value with a double value, which limits how the operator is used
* Use the member function overloads as follows:
Time operator* (double n) const;
This means that you can only use the operator a = B * 2.5-A = b.operator* (2.5) (note: The left operand should be the calling object)

If this is used, it causes compilation error A = 2.5 * B (the left operand is the calling object, and 2.5 is not an object)

This can be resolved with a non-member function, which is defined as a friend function because of the access to private data:
friend time operator* (double N, const time & T);

at this point, A = 2.5 * B--and a = operator* (2.5,b)
for a non-member overloaded operator function, the operand to the left of the OP corresponds to the first parameter, and the operand to the right of the OP corresponds to the second argument.

Create friend:
A, the prototype of the friend function should be placed in the class declaration, and add friend keyword
friend time operator* (double N, const time & T);
operator* is declared in a class, but is not a member function of a class, but has the same access rights as a member function

B, the function is defined in the CPP file, because it is not a member function, so do not use:: Qualifier, and do not use the Friend keyword in the definition

Summary: The friend function of a class is a non-member function and has the same access rights as a class member function.

3. Common friends, overloading << operators
overloading << operators so that they can be combined with cout to output the contents of an object

Prototypes:
friend Std::ostream & operator<< (std::ostream & OS, const time & T);
The implementation is as follows:
Std::ostream & operator<< (std::ostream & OS, const time & T)
{
os << t.m_hours << ":" << t.m_minutes;
return OS;
}
This allows you to output the time object directly
Time T (10.50)
cout << t;

in general, to overload the << operator to display the C_name object, the UF meta function is defined as follows:
Ostream & operator<< (ostream & OS, const & C_name obj)
{
os << ...;//Output Object Contents
return OS;
}
The main function of returning ostream references is to splice the output, such as cout << "Current time:" << t << "\ n";


 



C + + Learning notes-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.