This assignment replaces lab 11.13 of a c++ how to program. Here's what you
ID: 3633647 • Letter: T
Question
This assignment replaces lab 11.13 of a c++ how to program. Here's what you need to do.Create a class called StrangeInt that manages a single integer. In this class you will override certain operators in a way that would be highly inadvisable in the "real world." You will learn how to overload operators, but you will also learn what kind of confusion can be created by choosing strange behaviors for standard operations. Specifically, in addition to the usual constructor, get- and set- methods, you will implement these four overloaded operators:
void operator+=(const StrangeInt& right);
void operator-=(const StrangeInt& right);
StrangeInt operator+(const StrangeInt& right) const;
StrangeInt operator-(const StrangeInt& right) const;
What makes this class strange is that operator+ and operator+= will MULTIPLY the two objects, and operator- and operator-= will DIVIDE the two objects. Write a main program that initializes a few StrangeInt objects and tests the four overloaded operators. For operator+, be sure to demonstrate that three objects can be added, like this: a = b + c + d
Explanation / Answer
Dear,
#include<iostream>
using namespace std;
//StrangeInt class
class StrangeInt
{
//class variables
int integer;
public:
//constructors
StrangeInt()
{}
StrangeInt(int i)
{
this->integer=i;
}
//overloading operators
void operator+=(const StrangeInt &right) ;
void operator-=(const StrangeInt &right) ;
StrangeInt operator+(const StrangeInt &right);
StrangeInt operator-(const StrangeInt &right);
};
//operator+ implementation
StrangeInt StrangeInt::operator+(const StrangeInt &right)
{
StrangeInt temp;
temp.integer= this->integer*right.integer;
return temp;
}
//operator +=implementation
void StrangeInt::operator+=(const StrangeInt &right)
{
integer*right.integer;
}
//operator- implementation
StrangeInt StrangeInt::operator-(const StrangeInt &right)
{
StrangeInt temp;
temp.integer=this->integer/right.integer;
return temp;
}
//operator -=implementation
void StrangeInt::operator-=(const StrangeInt &right)
{
integer/right.integer;
}
//main mehtod to implement four overloading operators
int main()
{
StrangeInt s1(5);
StrangeInt s2(4);
StrangeInt s;
//for operator +
s=s1+s2;
cout<
StrangeInt sobj=s1.operator+=(s2);
//for operator +=
cout<< sobj;
//for operator -
s=s1-s2;
StrangeInt sobj;
//for operator +=
cout<< s1.operator-=(s2);
system("pause");
return 0;
}
Hope this woudl helpful to you...