Sunday, November 27, 2022
HomeSoftware DevelopmentEnter/Output Operators Overloading in C++

Enter/Output Operators Overloading in C++


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 function due to which we are able to instantly use operators with user-defined lessons 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 Information 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 essential() 
{
    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 will be executed 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 instantly which makes code straightforward to know, and even code dimension decreases due to it. Additionally, operator overloading doesn’t have an effect on the traditional working of the operator however gives additional performance to it.

A easy instance is given beneath:

C++

#embrace <iostream>

utilizing namespace std;

  

class Fraction {

  

non-public:

    int numerator;

    int denominator;

  

public:

    

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

    {

        numerator = x;

        denominator = y;

    }

  

    

    

    pal istream& operator>>(istream& cin, Fraction& c)

    {

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

        return cin;

    }

  

    pal ostream& operator<<(ostream&, Fraction& c)

    {

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

        return cout;

    }

};

  

int essential()

{

    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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments