This Pointer: Operator Overloading
This Pointer: Operator Overloading
Operator overloading
Operator overloading is closely related to function overloading. In C++, you can
overload most operators so that they perform special operations relative to classes
that you create. For example, a class that maintains a stack might overload + to
perform a push operation and to perform a pop. When an operator is
overloaded, none of its original meanings are lost. After overloading the
appropriate operators, you can use objects in expressions in just the same way that
you use C++'s built-in data types. Operator overloading is done by creating
operator functions. An operator function defines the operations that the overloaded
operator will perform relative to the class upon which it will work. An operator
function is created using the keyword operator. Operator functions can be either
members or nonmembers of a class. Nonmember operator functions are almost
always friend functions of the class, however. The way operator functions are
written differs between member and nonmember functions.
This program creates a class called loc, which stores longitude and latitude values.
It overloads the + operator relative to this class.
#include<iostream>
classloc{
intlongitude,latitude;
public:
loc(){}
loc(intlg,intlt)
{
longitude=lg;
latitude=lt;
}
voidshow()
{
cout<<longitude<<"";
cout<<latitude<<"\n";
}
locoperator+(locop2);
};
//Overload+forloc.
locloc::operator+(locop2)
{
loctemp;
temp.longitude=op2.longitude+longitude;
temp.latitude=op2.latitude+latitude;
returntemp;
}
voidmain()
{
locob1(10,20),ob2(5,30);
ob1.show();//displays1020
ob2.show();//displays530
ob1=ob1+ob2;
ob1.show();//displays1550
getch();
}