2. This problem requires implementing four functions Given the following class d
ID: 3727990 • Letter: 2
Question
2. This problem requires implementing four functions Given the following class definition, non-member non-friend function, and explanation: class Foo public: Foo) Foo (int x, int y); int getLarge) const; int getSmall ) const; Foo& operator +); const Foo operat r++ (int ) ; friend const Foo operator +(const Foo &lhs;, const Foo &rhs;); private: int large; int small; const Foo operator -(const Foo &lhs;, const Foo &rhs;); Notes on how the class behaves: The variable large must always hold the highest value int . Increment will always only increment the smaller number . Addition adds the two large integers together, then the small integers Subtraction behaves similarly to addition, the large numbers are paired together, as are the small numbers Implement the four operator overloadsExplanation / Answer
#include <iostream>
using namespace std;
class Foo
{
public:
Foo(){ // default constructor
large = 0;
small = 0;
}
Foo(int x,int y)//argument constructor
{
large = x;
small = y;
}
//get methods
int getLarge() const
{
return large;
}
int getSmall() const
{
return small;
}
Foo& operator++() // overloading preincrement
{
Foo temp;
temp.large = ++this->large;
temp.small = ++this->small;
return temp;
}
const Foo operator++(int) // overloading postincrement
{
Foo temp;
temp.large = this->large++;
temp.small = this->small++;
return temp;
}
friend const Foo operator +(const Foo &lhs,const Foo &rhs); // friend function
private:
int large;
int small;
};
//overloading + and - operators
const Foo operator-(const Foo &lhs,const Foo &rhs)
{
int l= lhs.getLarge() - rhs.getLarge();
int s = lhs.getSmall() - rhs.getSmall();
Foo temp(l,s);
return temp;
}
const Foo operator +(const Foo &lhs,const Foo &rhs)
{
Foo temp;
temp.large = lhs.large + rhs.large; // friend function can access private data
temp.small = lhs.small + rhs.small;
return temp;
}
int main() {
Foo f(45,21);
cout<<"f : large "<<f.getLarge()<<" small "<<f.getSmall();
cout<<" Incrementing f:";
++f;
cout<<" f : large "<<f.getLarge()<<" small "<<f.getSmall();
Foo f1(21,19);
cout<<" f1 : large "<<f1.getLarge()<<" small "<<f1.getSmall();
cout<<" Incrementing f1:";
f1++;
cout<<" f1 : large "<<f1.getLarge()<<" small "<<f1.getSmall();
Foo f2;
cout<<" Difference of f and f1 : ";
cout<<" f - f1 : ";
f2 = f-f1;
cout<<" f2 : large "<<f2.getLarge()<<" small "<<f2.getSmall();
cout<<" Sum of f and f1 : ";
cout<<" f + f1 : ";
f2 = f+f1;
cout<<" f2 : large "<<f2.getLarge()<<" small "<<f2.getSmall();
return 0;
}
output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.