Pages

C++ Programming Tutorials -23(Friend Class)

tut27.cpp=
// This tut contains Friend Class in C++


#include <iostream>
using namespace std;

// Forward declaration
class Complex;

class Calculator
{
public:
    int add(int aint b)
    {
        return (a + b);
    }

    int sumRealComplex(ComplexComplex);
    int sumCompComplex(ComplexComplex);
};

class Complex
{
    int ab;
    // Individually declaring functions as friends
    // friend int Calculator ::sumRealComplex(Complex, Complex);
    // friend int Calculator ::sumCompComplex(Complex, Complex);

    // Aliter: Declaring the entire calculator class as friend
    friend class Calculator;

public:
    void setNumber(int n1int n2)
    {
        a = n1;
        b = n2;
    }

    void printNumber()
    {
        cout << "Your number is " << a << " + " << b << "i" << endl;
    }
};

int Calculator ::sumRealComplex(Complex o1Complex o2)
{
    return (o1.a + o2.a);
}

int Calculator ::sumCompComplex(Complex o1Complex o2)
{
    return (o1.b + o2.b);
}

int main()
{
    Complex o1o2;
    o1.setNumber(14);
    o2.setNumber(57);
    Calculator calc;
    int res = calc.sumRealComplex(o1o2);
    cout << "The sum of real part of o1 and o2 is " << res << endl;
    int resc = calc.sumCompComplex(o1o2);
    cout << "The sum of complex part of o1 and o2 is " << resc << endl;
    return 0;
}


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Top 10 Python Packages Every Developer Should Learn

Top 10 Python Packages Every Developer Should Learn There are more than  200,000 Python packages  in the world (and that’s just counting tho...