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

Material Type: Notes; Professor: Miller; Class: Object Oriented Programming for Engineers; Subject: Computer Systems Engineering ; University: University of Alaska - Anchorage; Term: Fall 2009;

Typology: Study notes

Pre 2010

Uploaded on 03/28/2010

koofers-user-0ie
koofers-user-0ie 🇺🇸

9 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSE294B
Object-Oriented C++ Programming for Engineers
Lecture #18
Jeffrey Miller, Ph.D.
pf3
pf4
pf5
pf8
pf9

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.