Docsity

Notes on Operator Overloading - Object Oriented Programming | CSE A215, Study notes of Engineering

Partial preview of the text

Download Notes on Operator Overloading - Object Oriented Programming | CSE A215 and more Study notes Engineering in PDF only on Docsity!

CSE294B

Object-Oriented C++ Programming for Engineers

Lecture

Jeffrey Miller, Ph.D.

Operator Overloading

Operator overloading allows certain operators tobe used for more than one purpose

The >> and << operators are both used for multiple purposes.. .what are they?

The +, –, *, and / operators are overloaded as well for use withintegers, floating point values, and pointers

In C++, we can overload operators for use with objects aswell

Float_Number Class

Assume we have the following class

class Float_Number { private: float fnum; public: Float_Number() { } Float_Number(float fnum) { setFloat(fnum); } float getFloat() { return fnum; } void setFloat(float fnum) { this->fnum = fnum; } };

Adding and Outputting Objects

Now assume that we want to be able to add twoFloat_Number variables together then output thevalue of the sum as follows

void main() {

Float_Number fnum1(3.0);

Float_Number fnum2(5.3);

Float_Number sum

fnum

fnum2;

cout <<

sum

endl;

Overloading << Operator

We need to overload the << operator so wecan output a Float_Number object

ostream& operator<< (ostream &output, Float_Number& f) { output << f.getFloat(); return output; }

Program

Write a program to compare two strings using the < and >operators.