Reload stream insertion operators and stream extraction Operators

Source: Internet
Author: User

The reload Function Format for "<" and ">" is as follows:

Istream & operator> (istream &, custom Class &);

Ostream & operator <(ostream &, custom Class &);

You can only use the ">" and "<" functions as friend functions or common functions, rather than defining them as member functions.

 1 # Include <iostream. h>
2
3 // Using namespace STD;
4
5 Class Complex
6 {
7 Public :
8 Friend ostream & Operator <(Ostream &, complex &);
9 Friend istream & Operator >>( Istream &, complex &);
10 Private :
11 Double Real;
12 Double Imag;
13 };
14
15 Ostream & Operator <(Ostream & output, complex & C)
16 {
17 Output < " ( " <C. Real;
18 If (C. imag> = 0 ) Output < " + " ;
19 Output <C. imag < " I) " <Endl;
20 Return Output;
21 }
22
23 Istream & Operator > (Istream & input, complex & C)
24 {
25 Cout < " Please input real part and imaginary part of Complex Number: " ;
26 Input> C. Real> C. imag;
27 Return Input;
28 }
29
30 Int Main ( Void )
31 {
32 Complex C1, C2;
33 Cin> C1> C2;
34 Cout < " C1 = " <C1 <Endl;
35 Cout < " C2 = " <C2 <Endl;
36 Return 0 ;
37 }

 

The compilation system interprets "cout <C":

Operator <(cout, c)

Call the following operator by using cout and C as real parameters <Function

Ostream & operator <(ostream & output, complex & C)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.