Monday, August 9, 2010

Operator Overloading: Block Example

Here is Block.h

#pragma once
/***********************
this class lets you set the height and width
of a 2 dimensional block and then defines
four operators that can work with those blocks
**********************************/
class Block
{
public:
Block(void);
Block (int x, int y); //overloaded constructor
~Block(void);
//sets and gets for the private members
void SetX(int);
int GetX();
void SetY(int);
int GetY();
int CalculateArea();
//declare operator overload methods
//these tell the compiler how to apply
//these operators to the Block Class
Block operator+(const Block &b2);
Block operator-(const Block &b2);
bool operator==(const Block &b2);
bool operator!=(const Block &b2);

private:
int x,y;
};

Here is Block.cpp

#include "Block.h"

Block::Block(void)
{
//set default constructor
SetX(0);
SetY(0);
}

Block::~Block(void)
{
}

//overloaded constructor
Block::Block(int x, int y)
{
SetX(x);
SetY(y);
}

//Create sets and gets
//for the variables
void Block::SetX(int x)
{
//the this pointer points the the
//member of the current instance
this->x=x;
}

int Block::GetX()
{
return x;
}

void Block::SetY(int y)
{
this->y=y;
}

int Block::GetY()
{
return y;
}

//calculate the area
int Block::CalculateArea()
{
return GetX() * GetY();
}

//define what it means to add two blocks
Block Block::operator +(const Block &b2)
{
Block temp;
temp.SetX(this->x+b2.x);
temp.SetY(this->y+b2.y);
return temp;
}

//Define what subtraction means
Block Block::operator -(const Block &b2)
{
Block temp;
temp.SetX(this->x-b2.x);
temp.SetY(this->y-b2.y);
return temp;
}

//define what makes two blacks equal
bool Block::operator ==(const Block &b2)
{
bool isEqual =false;
if (this->x==b2.x && this->y==b2.y)
{
isEqual=true;
}
return isEqual;
}

//define not equal
bool Block::operator !=(const Block &b2)
{
bool isEqual =false;
if (this->x!=b2.x || this->y!=b2.y)
{
isEqual=true;
}
return isEqual;
}

Here is program.cpp

#include <iostream>
#include "Block.h"
using namespace std;

void PauseIt()
{
cout << "enter any character and press Enter to exit"
<<endl;
char c;
cin >> c;
}
int main()
{
cout << "Enter a block height: ";
int h, w;
cin>> h;
cout<<endl;
cout << "Enter a block width: ";
cin >> w;
cout << endl;
Block b1(h,w);
cout << "Enter a block height: ";
cin>> h;
cout<<endl;
cout << "Enter a block width: ";
cin >> w;
cout << endl;
Block b2(h,w);

cout << "The area of Block 1 is " << b1.CalculateArea()
<< " the area of Block 2 is " << b2.CalculateArea()
<< endl;

Block b3 = b1 + b2;

cout << "The area of block three (b1 + b2) is "
<< b3.CalculateArea() << endl;

Block b4= b1 - b2;

cout << "The area of Block 4 (b1-b2) "
<< b4.CalculateArea() << endl;

Block b5(5,5);
Block b6(6,5);

if (b5==b6)
cout << "block 5 and 6 are equal" << endl;
else
cout << "Block 5 and 6 are unequal" << endl;

PauseIt();

}

No comments:

Post a Comment