Objects as Function Arguments -by reference


#include <iostream.h>
#include<conio.h>

class Rational
{
    int numerator;
    int denominator;
public :
        void set(int, int); // prototypes declared
        void print();
        void exchange (Rational*);
};
void Rational::set(int a, int b)
{
    numerator = a;
    denominator = b;
}

void Rational::print()
{
    cout << numerator << " / " << denominator;
    cout << "\n";
}

void Rational::exchange(Rational *n1)
{                                   
    int temp = 0;
    temp=numerator;
    numerator=(*n1).numerator;
    (*n1).numerator=temp;

    temp=denominator;
    denominator=(*n1).denominator;
    (*n1).denominator=temp;
}

void main(void)
{
    Rational a, b;
    clrscr();
    a.set(2,5);
    b.set(3,7);
    a.exchange(&b);        // Objects passed as arguments
    cout << "a = "; a.print();
    cout << "b = "; b.print();
    getch();
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|