Header Ads Widget

Ticker

6/recent/ticker-posts

Practical 10 OOP

 PRACTICAL – 10.1

Write a program to overload the + and == operators for the string class.

#include <iostream>
#include <string>
using namespace std;
class Operator_ovr
{
    string s1, s2;

public:
    void operator+()
    {
        string total;
        total = this->s1 + this->s2;
        cout << total << endl;
    }
    Operator_ovr() {}
    Operator_ovr(string one, string two)
    {
        s1 = one;
        s2 = two;
    }
    void operator==(Operator_ovr str)
    {
        if (s1 == str.s1)
            cout << "string are same";
        else
            cout << "string are not same";
    }
};
int main()
{
    Operator_ovr j("jinay", "rahi"), r("shah", "patel");
    +j;
    j == r;
    return 0;
}

PRACTICAL – 10.2

Write a program to overload the [] operator.

#include <iostream>
using namespace std;
const int SIZE = 10;
class safearay
{
private:
    int arr[SIZE];

public:
    safearay()
    {
        register int i;
        for (i = 0; i < SIZE; i++)
        {
            arr[i] = i;
        }
    }
    int &operator[](int i)
    {
        if (i > SIZE)
        {
            cout << "Index out of bounds" << endl;
            // return first element.
            return arr[0];
        }

        return arr[i];
    }
};
int main()
{
    safearay A;
    cout << "Value of A[2] : " << A[2] << endl;
    cout << "Value of A[5] : " << A[5] << endl;
    cout << "Value of A[12] : " << A[12] << endl;
    return 0;
}

PRACTICAL – 10.3

Write a program to overload the << and >> operators.

#include <iostream>
using namespace std;
class Io
{
    int age;

public:
    Io()
    {
        age = 0;
    }
    Io(int a)
    {
        age = a;
    }
    friend ostream &operator<<(ostream &output, const Io &D)
    {
        output << "Age is " << D.age << endl;
        return output;
    }

    friend istream &operator>>(istream &input, Io &D)
    {
        cout << "Enter Age : ";
        input >> D.age;
        return input;
    }
};
int main()
{
    Io jinay, kit(18);
    cin >> jinay;
    cout << jinay;
    cout << kit;
    return 0;
}

Post a Comment

0 Comments