COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button
C++ LANGUAGE INPUT/OUTPUT OPERATORS OVERLOADING
Input/Output Operators Overloading
C++ is able to input and output the built-in data types using
the stream extraction operator >> and the stream
extraction operators also can be overloaded to perform input
insertion operator <<. The stream insertion and stream
and output for user-defined types like an object.
friend of the class because it would be called without creating an object.
Here, it is important to make operator overloading function a
Following example explains how extraction operator >>
and insertion operator <<.
public:
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
friend ostream &operator<<( ostream &output,
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
}
const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
Distance D1(11, 10), D2(5, 11), D3;
friend istream &operator>>( istream &input, Distance &D )
{
input >> D.feet >> D.inches;
return input;
}
};
int main()
{
cout << "Enter the value of object : " << endl;
When the above code is compiled and executed, it produces the following result:
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
return 0;
}
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
No comments:
Post a Comment