Enter/Output Operators Overloading in C++

[ad_1]

View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Operator Overloading is part of Polymorphism, which allows the characteristic due to which we are able to straight use operators with user-defined lessons and objects.

To learn extra about this, check with the article operator overloading in C++.

Enter/Output Operators(>>/<<) Overloading in C++

We are able to’t straight use the Enter/Output Operators (>>/<<) on objects. The easy rationalization for that is that the Enter/Output Operators (>>/<<) are predefined to function solely on built-in Knowledge sorts. As the category and objects are user-defined information sorts, so the compiler generates an error.

Instance:

int a;
cin>>a;
cout<<a<<endl;

right here, Enter/Output Operators (>>/<<)  can be utilized straight as built-in information sorts.

Instance:

class C{

};

int foremost() 
{
    C c1;
    cin>>c1;
    cout<<c1;
    return 0;
}

c1 are variables of sort “class C”. Right here compiler will generate an error as we are attempting to make use of Enter/Output Operators (>>/<<) on user-defined information sorts.

Enter/Output Operators(>>/<<) are used to enter and output the category variable. These may be performed utilizing strategies however we select operator overloading as an alternative. The rationale for that is, operator overloading offers the performance to make use of the operator straight which makes code simple to know, and even code measurement decreases due to it. Additionally, operator overloading doesn’t have an effect on the traditional working of the operator however supplies further performance to it.

A easy instance is given under:

C++

#embrace <iostream>

utilizing namespace std;

  

class Fraction {

  

personal:

    int numerator;

    int denominator;

  

public:

    

    Fraction(int x = 0, int y = 1)

    {

        numerator = x;

        denominator = y;

    }

  

    

    

    good friend istream& operator>>(istream& cin, Fraction& c)

    {

        cin >> c.numerator >> c.denominator;

        return cin;

    }

  

    good friend ostream& operator<<(ostream&, Fraction& c)

    {

        cout << c.numerator << "/" << c.denominator;

        return cout;

    }

};

  

int foremost()

{

    Fraction x;

    cout << "Enter a numerator and denominator of "

            "Fraction: ";

    cin >> x;

    cout << "Fraction is: ";

    cout << x;

    return 0;

}

Output:

Enter a numerator and denominator of Fraction: 16 7
Fraction is: 16/7

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *