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 permits the characteristic due to which we will instantly use operators with user-defined courses and objects.

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

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

We are able to’t instantly use the Enter/Output Operators (>>/<<) on objects. The straightforward 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 instantly as built-in information sorts.

Instance:

class C{

};

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

c1 are variables of kind “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 might be performed utilizing strategies however we select operator overloading as an alternative. The explanation for that is, operator overloading provides the performance to make use of the operator instantly which makes code straightforward to know, and even code measurement decreases due to it. Additionally, operator overloading doesn’t have an effect on the conventional working of the operator however gives additional performance to it.

A easy instance is given beneath:

C++

#embody <iostream>

utilizing namespace std;

  

class Fraction {

  

non-public:

    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 predominant()

{

    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