Operator
overloading is a type of function name overloading. The syntax for defining
operator overloading is similar to the definition of the member function. An ‘operator
function’ is declared and defined. For this, the function name is replaced with
the keyword ‘operator’ followed by the operator to be overloaded. The general form
and syntax for operator overloading is :
return-type
class-name:: operator op (argument-list)
{
body of the function
}
Where
op is the operator to be overloaded. The function operator op() is called the
operator function. The return-type refers to the data type returned by the
operator function. The operator function can be declared as a member function
or a friend function.
/* Simple example to demonstrate the working of operator overloading*/
/* Simple example to demonstrate the working of operator overloading*/
#include <iostream>
class object
{
public:
int a;
int b;
object operator+(const object& obj); //declaration of overloaded function
void operator=(const object& obj);
};
void object::operator=(const object& obj)
{
(*this).a = obj.a;
(*this).b = obj.b;
return;
}
object object::operator+(const object& obj2) //definition of overloaded function
{
object tmp_obj = *this;
tmp_obj.a = tmp_obj.a + obj2.a;
tmp_obj.b = tmp_obj.b + obj2.b;
return tmp_obj;
}
int main(void)
{
object obj1, obj2, obj3;
obj1.a = 1;
obj1.b = 1;
obj2.a = 2;
obj2.b = 2;
obj3.a = 0;
obj3.b = 0;
obj3 = obj1 + obj2;
std::cout<<obj3.a<<" "<<obj3.b<<"\n";
return 0;
}
Output:
3 3
0 comments:
Post a Comment