(1) (a)Define a class Pairs with two integer data members, f and s, where f represents
the first value in the ordered pair and s represents the second value in an ordered
pair. Write a program to test all the overloaded operators in your class definition.
(b) Overload the stream extraction operator >> and the stream insertion operator << as
friend functions so that objects of class Pairs are to be input and output in the
form (5,6) (5,-4) (-5,4) or (-5,-6).
(c) Overload binary operator + as a friend function to add pairs according to the rule
(a,b) + (c,d) = (a + c, b + d)
(d)Overload operator – as a friend function in the same way, i.e. according to the rule
(a,b) - (c,d) = (a - c, b - d)
(e) Overload operator * as a friend function on Pairs and int according to the rule
(a,b) * c = (a * c, b * c)
class Pair {
public:
Pair(int f, int s) {
this->f=f;
this->s=s;
}
Pair operator<< (int n) {
return Pair(this.f<<n, this.s<<n);
}
Pair operator>> (int n) {
return Pair(this.f>>n, this.s>>n);
}
int f;
int s;
};
Pair operator+(const Pair &a, const Pair &b) {
return Pair(a.f+b.f, a.s+b.s);
}
Pair operator-(const Pair &a, const Pair &b) {
return Pair(a.f-b.f, a.s-b.s);
}
Pair operator*(const Pair &a, int x) {
return Pair(a.f*x, a.s*x);
}
Comments
Leave a comment