Write a program to overload operators in the same program by writing suitable operator member
functions for following expression:
O7= ((O1 % O2)>(O3 || O4) - (O5>O6)) [Here O1,O2,O3,O4,O5,O6 and O7 are objects of a class
“overloading”, and this class is having one integer data member]
#include <iostream>
class Overloading {
private:
int value;
public:
Overloading(int val = 0) : value(val) {}
// Although type of expression (O1 % O2) > (O3 || O4) - (O5 > O6) is boolean,
// it will be automatically converted to integer (true -> 1, false -> 0),
// then passed into constructor to create temporary object,
// then following assignment operator will be called with created object
// Here is returning reference (Overloading& instead of simply Overloading)
// because we don't want to create unnecessary copy of object
Overloading& operator =(const Overloading& right) {
value = right.value;
return *this;
}
Overloading operator %(const Overloading& right) {
return Overloading(value % right.value);
}
bool operator >(const Overloading& right) {
return value > right.value;
}
bool operator ||(const Overloading& right) {
return value || right.value;
}
// Here is passing a constant reference; reference, again, to make not
// an extra copy, and constant to make possible using of temporary objects
// as in expression (o[2] || o[3]) - (o[4] > o[5]), where (o[4] > o[5])
// is a temporary value that c++ forbids converting to a non-constant reference
Overloading operator -(const Overloading& right) {
return Overloading(value - right.value);
}
// Opearators for handy input and output Overloading objects
friend std::istream& operator >>(std::istream& is, Overloading& o) {
is >> o.value;
return is;
}
friend std::ostream& operator <<(std::ostream& os, const Overloading& o) {
os << o.value;
return os;
}
~Overloading() {}
};
int main() {
Overloading o[6];
std::cout << "Enter 6 integers separated by space: ";
for (int i = 0; i < 6; ++i) {
std::cin >> o[i];
}
Overloading result;
result = (o[0] % o[1]) > (o[2] || o[3]) - (o[4] > o[5]);
std::cout << "Result of (O1 % O2) > (O3 || O4) - (O5 > O6) is " << result << '\n';
return 0;
}
Comments
Leave a comment