overloading operators with class objects

Learning a programming language is hard enough without having to wrangle your computer into compiling and executing your code. From beginners to experts, the tips here will make life in C++ easier.
Post Reply
darknkreepy3#
Site Admin
Posts: 247
Joined: Tue Oct 27, 2009 9:33 pm

overloading operators with class objects

Post by darknkreepy3# »

Code: Select all

#include <cstdlib>
#include <iostream>

using namespace std;
//-----
class overloadEx
	{
	private:
		int amt;
	public:
		//default constructor
		overloadEx();
		overloadEx(int);
		
		int getAmt();
		void setAmt(int);
	
		//overload prefix
		void operator ++ ();
		//overload postfix
		void operator ++ (int);
		
		//overload the addition() operator (binary. a+b etc)
		overloadEx overloadEx::operator +(overloadEx theObj);
};
//*****definitions
//-----
overloadEx::overloadEx()
	{
	amt=0;
	}
//-----		
overloadEx::overloadEx(int startAmt)
	{
	amt=startAmt;
	}	
//-----
void overloadEx::operator ++ ()
	{
	++amt;
	}
//-----	
void overloadEx::operator ++ (int var)
	{
	++amt;
	}
//-----	
int overloadEx::getAmt()
	{
	return amt;
	}
//-----
void overloadEx::setAmt(int sentAmt)
	{
	amt=sentAmt;
	}

/*
thirdObj=firstobj+secondObj
*/
overloadEx overloadEx::operator +(overloadEx secondObj)
	{
	cout	<< "(+)overload example.\n";
	cout	<< "thirdObj=firstobj+secondObj\n\n";
	/*
	create a new overloadEx object to return
	call the default class fom here and make a new local object clled 'thirdObj'
	*/
	overloadEx thirdObj;
	/*
	the object to the left of the operator (+) is firstObj
	*/
	cout	<< "firstObj.amt=" << secondObj.amt << endl;
	/*
	'amt' alone refers to the first object on the left of the operator (+)
	*/
	thirdObj.setAmt(secondObj.amt + amt);
	//return the new obj, 'thirdObj'
	return thirdObj;
	}
//-----
int main()
{
    overloadEx test1;
    ++test1;
    ++test1;
    test1++;
	cout 	<< "test1 [amt]=" << test1.getAmt() << "\n";
	
	overloadEx test2;
	++test2;
	++test2;
	cout	<< "test2 [amt]=" << test2.getAmt() << "\n";
	
	//thirdObject=firstObj+secondObj
	overloadEx test3=test1+test2;
	cout	<< "test3 [thirdObj] [amt]=" << test3.getAmt() << "\n";
	
	system("PAUSE");
    return EXIT_SUCCESS;
}
Post Reply