Sie sind auf Seite 1von 9

FRIEND FUNCTIONS

To swap two numbers using friend function


#include <iostream.h> class two; class one { int value1; public: void indata(int a) { value1 = a; } void display(void) { cout << value1 ;} friend void exchange (one &, two &); }; }; class two { int value2; public: void indata(int a) { value1 = a; } void display(void) { cout << value2 ;} friend void exchange (one &, two &);

To swap two numbers using friend function


void exchange (one &x, two &y) { int temp = x.value1; x.value1 = y.value2; y.value2 = temp; } void main ( ) { one c1; two c2; c1.indata (100); c2.indata (200); cout << Values before exchange << \n; c1.display ( ); c2.display ( ); exchange(c1, c2); cout << Values after exchange << \n; c1.display ( ); c2.display ( ); }

To calculate the total salary of the family using friend function


class Wife; class Husband { private: long salary; public: void ReadData ( ) { cout << "\nEnter his salary.\n"; cin >> salary; } friend long tot_sal (Husband, Wife); }; class Wife { private: long salary; public: void ReadData ( ) { cout << "\nEnter her salary\n"; cin >> salary; } friend long tot_sal (Husband, Wife); };

To calculate the total salary of the family using friend function


long tot_sal (Husband H, Wife W) // Friend Function { return (H.salary + W.salary);} void main() { Husband H; Wife W; clrscr( ); H.ReadData( ); W.ReadData( ); cout << "\n Total Salary: << tot_sal(H,W); getch ( ); }

FRIEND CLASSES

Friend Class
 

Type friend class Classname in class granting friendship If ClassOne granting friendship to ClassTwo, friend class ClassTwo; appears in ClassOne's definition

Program to illustrate friend classes in C++


#include <iostream> class CSquare; class CRectangle { int width, height; public: int area ( ) {return (width * height);} void convert (CSquare a); }; }; void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle;

Program to illustrate friend classes in C++


int main ( ) { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area( ); return 0; }

Das könnte Ihnen auch gefallen