Friends and Operators

1 / 22

# Friends and Operators - PowerPoint PPT Presentation

B Smith: Review for final will be during the lab. Next class: inheritance. B Smith: Discuss project and ostream stuff. These items could be extra credit for the project!. Friends and Operators. B Smith: 5/16/05: Rate 3. Added information after the lecture. B Smith:

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Friends and Operators' - amelia

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

B Smith:

Review for final will be during the lab. Next class: inheritance.

B Smith:

Discuss project and ostream stuff. These items could be extra credit for the project!

### Friends and Operators

B Smith:

5/16/05: Rate 3. Added information after the lecture

B Smith:

Fall05: rate: 3 if sufficiet context for ostream& is provided. Time: 50 min

B Smith:

Covering derived classes more important?

Math 130Lecture # 35

Overview
• Friend Functions
• complex friends
• Operator Functions
• Stream Objects
• ostream&
Friend Functions
• Private class data members are accessible through the class’s member functions
• There are occasions when one class needs access to another class’s private data members
• To allow non-member functions access to the private data, make them friends
• put them on your list of friends
Complex Friends

class Complex

{

private:

double _real;

double _imag;

public:

Complex(double = 0, double = 0); // constructor

void display();

};

// friends list

// implementation section

Complex::Complex(double rl, double im)

{

_real = rl;

_imag = im;

}

void Complex::display()

{

char sign = '+';

if(_imag < 0) sign = '-';

cout << _real << sign << abs(_imag) << 'i';

return;

}

class Complex

{

// friends list

private:

double _real;

double _imag;

public:

Complex(double = 0, double = 0);

void display();

};

B Smith:

But they do not acces the private variables here? No need for privacy? Wrong! To add the real and imaginary parts in this manner, addreal must be able to see the private variables!

friend Implementations

class Complex

{

// friends list

private:

double _real;

double _imag;

public:

Complex(double = 0, double = 0);

void display();

};

// friend implementations

{

return(a._real + b._real);

}

{

return(a._imag + b._imag);

}

B Smith:

Turn the writing into info boxes

int main()

{

Complex a(3.2, 5.6), b(1.1, -8.4);

double re, im;

cout << "\nThe first complex number is ";

a.display();

cout << "\nThe second complex number is ";

b.display();

Complex c(re,im); // create a new Complex object

cout << "\n\nThe sum of these two complex numbers is ";

c.display();

cout << endl;

getchar();

return 0;

}

Friends
• A friend function
• A nonmember function in a class that has access to private (and protected) members of the classes
• Digression:
• Protected
• except for derived classes, protected variables are treated the same as if they were marked private
• in the derived class, the variable can be accessed by name
Operator Functions
• Other built-in operators can be overloaded

// class declaration (PGM 14.7)

class Date

{

private:

int month;

int day;

int year;

public:

Date(int = 7, int = 4, int = 2001); // constructor

int operator==(Date &); //declare the operator== function

void showdate(void); // member function to display a date

};

// class declaration

class Date

{

private:

int month;

int day;

int year;

public:

Date(int = 7, int = 4, int = 2001);

int operator==(Date &);

void showdate(void);

};

// implementation section

Date::Date(int mm, int dd, int yyyy)

{

month = mm;

day = dd;

year = yyyy;

}

int Date::operator==(Date &date2)

{

if(day == date2.day && month == date2.month && year == date2.year)

return (1);

else

return(0);

}

int main()

{

Date a(4,1,1999), b(12,18,2001), c(4,1,1999); // 3 objects

if (a == b)

cout << "Dates a and b are the same." << endl;

else

cout << "Dates a and b are not the same." << endl;

if (a == c)

cout << "Dates a and c are the same." << endl;

else

cout << "Dates a and c are not the same." << endl;

return 0;

}

// class declaration (PGM 14.8)

class Date

{

private:

int month;

int day;

int year;

public:

Date(int = 7, int = 4, int = 2001); // constructor

Date operator+(int); // overload the + operator

void showdate(); // to display a date

};

Date Date::operator+(int days)

{

Date temp; // a temporary date object to store the result

temp.day = day + days; // add the days

temp.month = month;

temp.year = year;

while (temp.day > 30) // now adjust the months

{

temp.month++;

temp.day -= 30;

}

while (temp.month > 12) // adjust the years

{

temp.year++;

temp.month -= 12;

}

return temp; // the values in temp are returned

}

B Smith:

Stopped here on 5/16/05, 2nd to last class of the semester.

int main()

{

Date a(4,1,1999), b; // declare two objects

cout << "The initial date is ";

a.showdate();

b = a + 284; // add in 284 days = 9 months and 14 days

cout << "The new date is ";

b.showdate();

return 0;

}

Why do we need friends?
• What we are doing now
• What we really want is to be able to output information in the following format:
• The problem is that << only knows how to output int, char, float, double, etc.

cout << "The initial date is ";

a.showdate(); // or a.toString();

cout << “The initial date is ” << a << endl;

#ifndef POINT_H

#define POINT_H

#include <iostream>

using namespace std;

class Point

{ public:

Point(double=0.0,double=0.0); // default constructor

Point(const Point&); // copy constructor

~Point(); // destructor

Point& operator=(const Point&); // assignment operator

double getX() const;

double getY() const;

string toString() const;

private:

double _x, _y;

};

#endif // POINT_H

#include "Point.h" // defines Point class

#include <sstream> // defines ostringstream class

Point::Point(double x, double y) : _x(x), _y(y) { }

Point::Point(const Point& p) : _x(p._x), _y(p._y) { }

Point::~Point() { }

Point& Point::operator=(const Point& p)

{ _x = p._x;

_y = p._y;

return *this;

}

double Point::getX() const

{ return _x;

}

double Point::getY() const

{ return _y;

}

string Point::toString() const

{ ostringstream output;

output << "(" << _x << "," << _y << ")";

return output.str();

}

B Smith:

Why can’t we simply use :

cout << p1 << endl; ?

Because the object cout is overloaded to work with data types int, char, float,…. But for new, ADT, of our own definition, we need to tell .operator<< how to print it. Typically, we will format the output to be a string since cout.operator<<(string) works for strings. First we will declare an ostream& myOs; and then use the functions of ostream, eg. myOs.str();

#include <iostream>

using namespace std;

#include "Point.h" // defines Point class

int main()

{ Point p0; // invokes default constructor

cout << "p0 = " << p0.toString() << "\n";

Point p1(5,-2); // invokes default constructor

cout << "p1 = " << p1.toString() << "\n";

Point p2=p1; // invokes copy constructor

cout << "p2 = " << p2.toString() << "\n";

p0 = p1; // invokes assignment operator

cout << "p0 = " << p0.toString() << "\n";

cout << "p0.x() = " << p0.getX() << "\n";

cout << "p0.y() = " << p0.getY() << "\n";

getchar();

}

class Point

{ friendostream& operator<<(ostream&, const Point&);

public:

Point(double=0.0,double=0.0); // default constructor

Point(const Point&); // copy constructor

Point& operator=(const Point&); // assignment operator

double getX() const;

double getY() const;

string toString() const;

protected:

double _x, _y;

};

ostream& operator<<(ostream& ostr, const Point& point)

{ return ostr << point.toString();

}

With this additional function, clients can output Point objects like this:

cout << “po = “ << p0 << “, p1 =“ << p1 << “, and p2 = “ << p2 << endl;

Clients can now output Point objects like this:

cout << “po = “ << p0 << “, p1 =“ << p1 << “, and p2 = “ << p2 << endl;

po=(0,0), p1=(1, 0), and p2=(5, -2)

Summary
• Friend Functions
• a friend is not a member function
• a friend is an ordinary function with extraordinary access to the data members of the class
• The most common kinds of friend functions are overloaded operators
• Operator Functions