self-test exercise 17 asked you to overload the operator >> and the operator <<
ID: 3637310 • Letter: S
Question
self-test exercise 17 asked you to overload the operator >> and the operator << for a class pairs. Complete and test this exercise. Implement the default constructor and the constructors with one and two int parameters. The one parameter constructor should initialize the first member of the pair; the second member of the pair is to be 0.Overload binary operator to add pairs according to the rule
(a, b) (c, d) = (a c, b d)
Overload operator- analogously.
Overload operator* on pairs and int according to the rule
(a, b)*c= (a*c, b*c)
Write a program to test all the member functions and overloaded operators in your class definition.
This is out of the Problem solving with c 8th edition chapter 11 pgs. 676-678.
Explanation / Answer
Dear,
//Header file section
#include <iostream>
using namespace std;
//class pair declaration
class Pair
{
public:
Pair();
Pair(int first, int second);
Pair(int first);
int accessFirst();
int accessSecond();
// friend and operator overloaded functions
friend Pair operator+(const Pair&, const Pair&);
friend Pair operator*(const Pair&, int);
friend istream& operator>> (istream&, Pair&);
friend ostream& operator<< (ostream&, const Pair&);
private:
int f;
int s;
};
// operator function definitions
Pair operator+(const Pair& lhs, const Pair& rhs)
{
return Pair(lhs.f + rhs.f, lhs.s + rhs.s);
}
Pair operator*(const Pair& lhs, int rhs)
{
return Pair(lhs.f * rhs, lhs.s * rhs);
}
istream& operator>> (istream& ins, Pair& second)
{
char ch;
ins >> ch;
ins >> second.f;
ins >> ch;
ins >> second.s;
ins >> ch;
return ins;
}
ostream& operator<< (ostream& outs, const Pair& second)
{
outs << '(';
outs << second.f;
outs << ", " ;
outs << second.s;
outs << ")";
return outs;
}
//parameterized constructor
Pair::Pair(int firstValue, int secondValue):
f(firstValue), s(secondValue)
{// deliberately empty
}
//single parameter costructor
Pair::Pair(int firstValue):f(firstValue), s(0)
{// deliberately empty
}
//default constructor
Pair::Pair(): f(0), s(0)
{}
//member function definitions
int Pair::accessFirst()
{
return f;
}
int Pair::accessSecond()
{
return s;
}
int main()
{
//object creation and setting values
Pair a(8,5);
Pair b(2,3);
Pair c(4,8);
Pair d,X,Y;
//function call to access values of c
cout<<"("<< c.accessFirst()<<","
<< c.accessSecond()<<")"<<endl;
cout << endl;
cout << "a " << a << endl
<< "b " << b << endl
<< "c " << c
<< endl << endl;
//function call to add two pairs
cout << "a + c : " << a+c << endl;
//function call to multiply pair with int value
cout << "b * 2: " << b * 2 << endl;
//pause system for a while
system("pause");
return 0;
}//end main
Hope this will help you..
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.