Operator Overloading

// operator '+' with polar coordinates

#include <iostream>

#include <cmath> //for sin(), cos(), etc.

using namespace std;

////////////////////////////////////////////////////////////////

class Polar

{

private:

double radius; //distance

double angle; //angle in radians

double getx() //these two functions

{ return radius*cos(angle); } //convert this Polar

double gety() //object into x and y

{ return radius*sin(angle); } //rectangular coords

public:

//--------------------------------------------------------------

Polar() //constructor, no args

{ radius=0.0; angle=0.0; }

//--------------------------------------------------------------

Polar(double r, double a) //constructor, two args

{ radius=r; angle=a; }

//--------------------------------------------------------------

void display() //display

{ cout << "(" << radius

<< ", " << angle << ")"; }

//--------------------------------------------------------------

Polar operator + (Polar p2) //add two Polars

{

double x = getx() + p2.getx(); //add x and y coords

double y = gety() + p2.gety(); //for this and p2

double r = sqrt(x*x + y*y); //convert new x and y

double a = atan(y/x); // to Polar

return Polar(r, a); //return temp Polar

}

};

////////////////////////////////////////////////////////////////

int main()

{

Polar p1(10.0, 0.0); //line to the right

Polar p2(10.0, 1.570796325); //line straight up

Polar p3; //uninitialized Polar

p3 = p1 + p2; //add two Polars

cout << "\np1="; p1.display(); //display all Polars

cout << "\np2="; p2.display();

cout << "\np3="; p3.display();

cout << endl;

system (“pause”);

return 0;

}


// creates bMoney class to represent monetary quantities

// includes member functions for input, output, and addition

#include <iostream>

#include <cmath> //for fabsl()

#include <string>

#include <process.h> //for exit()

#include <cstdio> //for sprintf()

using namespace std;

//9,999,999,999,999,990.0

const double LIMIT = 9999999999999990.0;

enum posneg { NEG, POS }; //sign

double mstold(string); //money string to long double

string ldtoms(long double); //long double to money string

//--------------------------------------------------------------

//convert string of digits to long double

//assumes no commas or '$' in string

double atold(string str)

{

double ldtemp = 0.0, dpDigit = 0.0;

for(int j=0; j<str.size(); j++) //for each character,

{

if(str[j]=='.') //if it's decimal point,

dpDigit = 10; //remember it

else if(dpDigit > 0) //was decimal point

{ //add digit divided by 10

ldtemp += (str[j]-'0') / dpDigit;

dpDigit *= 10.0; //increase divisor

if(dpDigit > 100) //no more than 2 dec places

break;

}

else //no decimal point yet

{

if(j > 0) //except first digit,

ldtemp *= 10.0; //multiply by 10

ldtemp += str[j]-'0'; //add new digit

}

} //end while

return ldtemp;

} //end atold()


////////////////////////////////////////////////////////////////

class bMoney

{

private:

double money; //holds money value

public:

bMoney() //no-arg constructor

{ money = 0.0; }

bMoney(string s) //1-arg constructor

{ money = mstold(s); }

void madd(bMoney, bMoney); //add two bMoneys

void getmoney(); //input

void putmoney(); //output

};

//--------------------------------------------------------------

//overloaded + operator: add two bMoneys

void bMoney::madd(bMoney m1, bMoney m2)

{

money = m1.money + m2.money; //add the long doubles

if(money > LIMIT || money < -LIMIT)

{ cout << "\nbMoney add overflow"; exit(0); }

}

//--------------------------------------------------------------

// input

void bMoney::getmoney()

{

char ustring[80];

cin >> ustring; // get money string from user

money = mstold(ustring); // give bMoney m this value

}

//--------------------------------------------------------------

// output

void bMoney::putmoney()

{ // convert to money string

cout << ldtoms(money); // and display

}

//--------------------------------------------------------------

//mstold()

//converts money string ("$123,456.55") to long double

double mstold(string str)

{

double ldtemp;

string tstring; //string with ',' and '$' removed

int j, k=0;

posneg sign = POS;

//remove commas, period, and minus sign (or parentheses)

for(j=0; j<str.size(); j++)

{

if( str[j]=='.' || (str[j]>='0' && str[j]<='9') )

tstring += str[j];

else if( str[j]=='-' || str[j]=='(' ) //check for minus

sign = NEG;

}

ldtemp = atold(tstring); //call homemade conversion

if(ldtemp > LIMIT)

{ cout << "\nbMoney input overflow"; exit(1); }

if(sign==NEG) //return negative

return (-1 * ldtemp);

else

return (ldtemp);

}

//--------------------------------------------------------------

//converts a long double to a money string ("$123,456.55")

string ldtoms(double ld)

{

string ostring;

char ustring[80]; //char* string for sprintf()

bool digitFlag;

char digit;

double templd;

int k = 0;

if(ld > LIMIT || ld < -LIMIT)

{ cout << "\nbMoney conversion overflow"; exit(0); }

ostring = "$"; //always start with '$'

if(ld < 0.0) //if negative number

ostring += '('; // enclose in parentheses

templd = fabsl(ld); //templd never negative

digitFlag = false;

sprintf(ustring, "%19.2f", templd); //string (no commas)

for(int j=0; j<19; j++) //for each character

{

digit = ustring[j]; //get character

if(digit != ' ') //set flag for first

digitFlag = true; // non-blank digit

if(digitFlag || j>16) //if any non-blanks

{

ostring += digit; //store the digit

if( !(j%3) && j<15 ) //every three digits,

ostring += ','; // store comma

} //end if(any non-blanks)

} //end for(j)

if(ld < 0.0) //if negative number

ostring += ')'; // enclose in parens

return ostring; //return output string

}

////////////////////////////////////////////////////////////////

int main()

{

bMoney mo1, mo2, moans;

char yesno = 'y';

while(yesno != 'n')

{

cout << "\nEnter first money amount: ";

mo1.getmoney();

cout << "\nEnter second money amount: ";

mo2.getmoney();

moans.madd(mo1, mo2); //add two bMoney objects

cout << "\nSum=";

moans.putmoney();

cout << "\nDo another (y/n)? ";

cin >> yesno;

}

return 0;

}


// creates bMoney class to represent monetary quantities

// includes member functions for input, output, and addition

#include <iostream>

#include <cmath> //for fabsl()

#include <cstring>

#include <process.h> //for exit()

#include <cstdio> //for sprintf()

using namespace std;

//9,999,999,999,999,990.0

const double LIMIT = 9999999999999990.0;

enum posneg { NEG, POS }; //sign

double mstold(string); //money string to long double

string ldtoms(double); //long double to money string

//--------------------------------------------------------------

//convert string of digits to long double

//assumes no commas or '$' in string

double atold(string str)

{

double ldtemp = 0.0, dpDigit = 0.0;

for(int j=0; j<str.size(); j++) //for each character,

{

if(str[j]=='.') //if it's decimal point,

dpDigit = 10; //remember it

else if(dpDigit > 0) //was decimal point

{ //add digit divided by 10

ldtemp += (str[j]-'0') / dpDigit;

dpDigit *= 10.0; //increase divisor

if(dpDigit > 100) //no more than 2 dec places

break;

}

else //no decimal point yet

{

if(j > 0) //except first digit,

ldtemp *= 10.0; //multiply by 10

ldtemp += str[j]-'0'; //add new digit

}

} //end while

return ldtemp;

} //end atold()

////////////////////////////////////////////////////////////////

class bMoney

{

private:

double money; //holds money value

public:

bMoney() //no-arg constructor

{ money = 0.0; }

bMoney(string s) //1-arg constructor

{ money = mstold(s); }

bMoney operator + (bMoney); //add two bMoneys

void getmoney(); //input

void putmoney(); //output

};

//--------------------------------------------------------------

//overloaded + operator: add two bMoneys

bMoney bMoney::operator + (bMoney m2)

{

double summoney;

summoney = money + m2.money; //add the long doubles

if(summoney > LIMIT || summoney < -LIMIT)

{ cout << "\nbMoney add overflow"; exit(0); }

return bMoney(ldtoms(summoney));

}

//--------------------------------------------------------------

// input

void bMoney::getmoney()

{

char ustring[80];

cin >> ustring; // get money string from user

money = mstold(ustring); // give bMoney m this value

}

//--------------------------------------------------------------

// output

void bMoney::putmoney()

{ // convert to money string

cout << ldtoms(money); // and display

}

//--------------------------------------------------------------

//mstold()

//converts money string ("$123,456.55") to long double

double mstold(string str)

{

double ldtemp;

string tstring; //string with ',' and '$' removed

int j, k=0;

posneg sign = POS;

//remove commas, period, and minus sign (or parentheses)

for(j=0; j<str.size(); j++)

{

if( str[j]=='.' || (str[j]>='0' && str[j]<='9') )

tstring += str[j];

else if( str[j]=='-' || str[j]=='(' ) //check for minus

sign = NEG;

}

ldtemp = atold(tstring); //call homemade conversion

if(ldtemp > LIMIT)

{ cout << "\nbMoney input overflow"; exit(1); }

if(sign==NEG) //return negative

return (-1 * ldtemp);

else

return (ldtemp);

}

//--------------------------------------------------------------

//converts a long double to a money string ("$123,456.55")

string ldtoms(double ld)

{

string ostring;

char ustring[80]; //char* string for sprintf()

bool digitFlag;

char digit;

double templd;

int k = 0;

if(ld > LIMIT || ld < -LIMIT)

{ cout << "\nbMoney conversion overflow"; exit(0); }

ostring = "$"; //always start with '$'

if(ld < 0.0) //if negative number

ostring += '('; // enclose in parentheses

templd = fabsl(ld); //templd never negative

digitFlag = false;

sprintf(ustring, "%19.2f", templd); //string (no commas)

for(int j=0; j<19; j++) //for each character

{

digit = ustring[j]; //get character

if(digit != ' ') //set flag for first

digitFlag = true; // non-blank digit

if(digitFlag || j>16) //if any non-blanks

{

ostring += digit; //store the digit

if( !(j%3) && j<15 ) //every three digits,

ostring += ','; // store comma

} //end if(any non-blanks)

} //end for(j)

if(ld < 0.0) //if negative number

ostring += ')'; // enclose in parens

return ostring; //return output string

}

////////////////////////////////////////////////////////////////

int main()

{

bMoney mo1, mo2, moans;

char yesno = 'y';

while(yesno != 'n')

{

cout << "\nEnter first money amount: ";

mo1.getmoney();

cout << "\nEnter second money amount: ";

mo2.getmoney();

moans = mo1 + mo2; //add two bMoney objects

cout << "\nSum=";

moans.putmoney();

cout << "\nDo another (y/n)? ";

cin >> yesno;

}

return 0;

}
// creates safe array (index values are checked before access)

// overloaded [] operator for both put and get

// uses inheritance to add lower and upper bounds specification

#include <iostream.>

#include <process.h> // for exit()

using namespace std;

const int LIMIT = 3; // array size

////////////////////////////////////////////////////////////////

class safearay

{

protected:

int arr[LIMIT];

public:

int& operator [](int n) //overloaded []

{

if( n< 0 || n>=LIMIT )

{ cout << "\nIndex out of bounds\n"; system("Pause"); exit(1); }

return arr[n];

}

};

////////////////////////////////////////////////////////////////

class safelo : public safearay

{

private:

int lower;

int upper;

public:

//--------------------------------------------------------------

safelo() // no-arg constructor

{ lower = upper = 0; }

//--------------------------------------------------------------

safelo(int l, int u) // 2-arg constructor

{

lower = l; upper = u;

if(upper-lower > LIMIT-1)

{

cout << "\nSpecified range " << lower << " to "

<< upper << " is too large\n";

system("pause");

exit(1);

}

}

//--------------------------------------------------------------

int& operator [](int n) // overloaded []

{

if( n<lower || n>upper )

{

cout << "\nIndex " << n << " is out of bounds\n";

system("Pause");

exit(1);

}

return arr[n-lower];

} };

////////////////////////////////////////////////////////////////

int main()

{

int lower=10, upper=12;

// int lower=10, upper=13; // range too big

safelo sa1(lower, upper);

// for(int j=lower; j<=upper; j++) // insert elements

for(int j=lower; j<=upper+1; j++) // too high

sa1[j] = j*10;

for(int j=lower; j<=upper; j++) // display elements

// for(j=lower-1; j<=upper; j++) // too low

{

int temp = sa1[j];

cout << "\nElement " << j << " is " << temp;

}

cout << endl;

system("pause");

return 0;

}



// overloaded '+' operator adds two times

#include <iostream.>

#include <iomanip.> //for setw()

using namespace std;

////////////////////////////////////////////////////////////////

class time

{

private:

int hrs, mins, secs;

public:

time() //no-arg constructor

{ hrs = mins = secs = 0; }

time(int h, int m, int s) //3-arg constructor

{ hrs=h; mins=m; secs=s; }

void display() //display time

{ //format 11:59:59

cout.fill('0'); //with leading zeros

cout << hrs

<< ':' << setw(2) << mins

<< ':' << setw(2) << secs;

}

time operator + (time); //add two times

time operator - (time); //subtract two times

time operator * (float);

//multiply time by float

}; //end time

//--------------------------------------------------------

time time::operator + (time t2) //add two times

{

int s = secs + t2.secs; //add seconds

int m = mins + t2.mins; //add minutes

int h = hrs + t2.hrs; //add hours

if( s > 59 ) //if secs overflow,

{ s -= 60; m++; } // carry a minute

if( m > 59 ) //if mins overflow,

{ m -= 60; h++; } // carry an hour

return time(h, m, s); //return temp value

}

//---------------------------------------------------------

time time::operator - (time t2) //subtract two times

{

int s = secs - t2.secs; //subtract seconds

int m = mins - t2.mins; //subtract minutes

int h = hrs - t2.hrs; //subtract hours

if( s < 0 ) //if secs underflow,

{ s += 60; m--; } // carry a minute

if( m <0 ) //if mins underflow,

{ m += 60; h--; } // carry an hour

return time(h, m, s); //return temp value

}

//---------------------------------------------------------

time time::operator * (float f) //multiply time by float

{

float remains;

//convert to float

float ftemp = (float) hrs*3600 + mins*60

+ secs;

float product = f * ftemp; //multiply

int h = int(product/3600); //convert to time

remains = product - float(h)*3600;

int m = int(remains/60);

remains = remains - float(m)*60;

int s = int(remains);

return time(h, m, s); //return time

}

////////////////////////////////////////////////////////////////

int main()

{

time time1(5, 0, 59); //create and initialze

time time2(4, 1, 1); // two times

time time3; //create another time

float f1 = 3.0;

cout << "\ntime1 = "; time1.display();

cout << "\ntime2 = "; time2.display();

time3 = time1 + time2; //add two times

cout << "\nSum = "; time3.display();

time3 = time1 - time2; //subtract two times

cout << "\nDifference = "; time3.display();

time3 = time1 * f1; //multiply time by float

cout << "\ntime1 * 3 = ";

time3.display();

cout << endl;

return 0;

}



// overloaded '+' operator adds two times

#include <iostream>

#include <iomanip> //for setw()

////////////////////////////////////////////////////////////////

class time

{

private:

int hrs, mins, secs;

public:

time() //no-arg constructor

{ hrs = mins = secs = 0; }

//--------------------------------------------------------

time(int h, int m, int s) //3-arg constructor

{ hrs=h; mins=m; secs=s; }

//---------------------------------------------------------

void display() //format 11:59:59

{

cout.fill('0'); //with leading zeros

cout << hrs

<< ':' << setw(2) << mins

<< ':' << setw(2) << secs;

}

//--------------------------------------------------------

time operator + (time t2) //add two times

{

int s = secs + t2.secs; //add seconds

int m = mins + t2.mins; //add minutes

int h = hrs + t2.hrs; //add hours

if( s > 59 ) //if secs overflow,

{ s -= 60; m++; } // carry a minute

if( m > 59 ) //if mins overflow,

{ m -= 60; h++; } // carry an hour

return time(h, m, s); //return temp value

}

//-------------------------------------------------------

time operator ++ () //overloaded ++ (prefix)

{

++secs; //increment seconds

if( secs > 59 ) //if secs overflow,

{ secs -= 60; mins++; } //carry a minute

if( mins > 59 ) //if mins overflow,

{ mins -= 60; hrs++; } // carry an hour

return time(hrs, mins, secs);

}

//-------------------------------------------------------

time operator ++ (int) //overloaded++(postfix)

{

time temp = time(hrs, mins, secs);

++secs; //increment seconds

if( secs > 59 ) //if secs overflow,

{ secs -= 60; mins++; } //carry a minute

if( mins > 59 ) //if mins overflow,

{ mins -= 60; hrs++; } // carry an hour

return temp; //return original time

}

//-------------------------------------------------------

time operator -- () //overloaded -- (prefix)

{

--secs; //decrement seconds

if( secs < 0 ) //if secs underflow,

{ secs += 60; mins--; } //carry a minute

if( mins < 0 ) //if mins underflow,

{ mins += 60; hrs--; } //carry an hour

return time(hrs, mins, secs);

//return new time

}

//---------------------------------------------------------

time operator -- (int) //overloaded--(postfix)