Exercise -3 (Operator Overloading)
a) Write a program to Overload Unary, and Binary Operators as Member Function, and Non Member Function.
i) Unary operator as member function
ii) Binary operator as non member function
b) Write a C ++ program to implement the overloading assignment = operator
Exercise -3 a-i)
Using a member function to overload an unary operator
Following program demonstrates overloading unary minus operator using a member function:
#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number(int x)
{
this->x = x;
}
void operator -()
{
x = -x;
}
void display()
{
cout<<"x = "<<x;
}
};
int main()
{
Number n1(10);
-n1;
n1.display();
return 0;
}
Output of the above program is as follows:
x = -10
When a friend function is used to overload an unary operator following points must be taken care of:
- The function will take one operand as a parameter.
- The operand will be an object of a class.
- The function can access the private members only though the object.
- The function may or may not return any value.
- The friend function will not have access to the this
#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number(int x)
{
this->x = x;
}
friend Number operator -(Number &);
void display()
{
cout<<"x = "<<x<<endl;
}
};
Number operator -(Number &n)
{
return Number(-n.x);
}
int main()
{
Number n1(20);
Number n2 = -n1;
n2.display();
return 0;
}
Output of the above program is as follows:
x = -20;
Exercise -3 a-ii)
ii) Binary operator as non member function
#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number() {}
Number(int x)
{
this->x = x;
}
friend Number operator +(Number &, Number &);
void display()
{
cout<<"x = "<<x<<endl;
}
};
Number operator +(Number &n1, Number &n2)
{
Number temp;
temp.x = n1.x + n2.x;
return temp;
}
int main()
{
Number n1(20);
Number n2(10);
Number n3 = n1 + n2;
n3.display();
return 0;
}
Output of the above program is as follows:
x = 30
Following program demonstrates overloading the binary operator + using a member function:
#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number() {}
Number(int x)
{
this->x = x;
}
Number operator +(Number &n)
{
Number temp;
temp.x = x + n.x;
return temp;
}
void display()
{
cout<<"x = "<<x<<endl;
}
};
int main()
{
Number n1(20);
Number n2(10);
Number n3 = n1 + n2;
n3.display();
return 0;
}
Output of the above program is as follows:
x = 30
Exercise -3b
b) Write a C ++ program to implement the overloading assignment = operator
#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number(int p)
{
x = p;
}
Number operator =(Number &n)
{
return Number(n.x);
}
void display()
{
cout<<"x = "<<x;
}
};
int main()
{
Number n1(10);
Number n2 = n1;
n2.display();
return 0;
}
Output for the above program is as follows:
x = 10
No comments