1. Questions
In C + +, in the input and output operation, we first think of using cout, CIN, the two library operation statements to achieve, such as
cout << 8 << "Hello world!" << Endl;
Cin >> S;
Cout,cin are the class objects in the library ostream, IStream, respectively.
If you want to cout,cin to output or input a class object, will it be sufficient for this requirement? Obviously, the original cout is unlikely to satisfy the direct input output of a class object that we have customized,
But as long as we're <<, the >> operator overloads it to handle the custom class object.
2. Implement
There is a plural class:
classComplex {priate:intReal; intImag; Public: Complex (intR=0,intI=0): Real (R), Imag (i) {cout<< Real <<" + "<< Imag <<"I" ; cout<<"Complex class constructed." } }
int main () {
Complex C; Output:0+0i, complex class constructed.
cout << C; Error
return 0;
}
The reason cout << C in the main function above is an error, because cout itself does not support the processing of class objects, if you want it to be able to print the same class object, you have to overload the operator <<
#include <iostream>#include<string>classComplex {priate:intReal; intImag; Public: Complex (intR=0,intI=0): Real (R), Imag (i) {cout<< Real <<" + "<< Imag <<"I" ; cout<<"Complex class constructed." } //Overload global FunctionFriend Ostream &operator<< (Ostream & O,ConstComplex &c); Friend IStream&operator>> (IStream & I, Complex &c);} Ostream&operator<< (Ostream & O,ConstComplex &c) {o<< C.real <<"+"<< C.imag <<"I"; returno;} IStream&operator>> (IStream & I, Complex &c) { strings; I>> s;//Simillar to CIN >> s; input string format like as A+bi...//parse S and get the real and imagC. Real =Real; C.imag=Imag; returni;}
The operator << is overloaded, and after the >> operation, it is possible to perform input and output operations on the class complex directly, such as
int main{ Complex C, C1; >> C; Input:3+4i complex output. " ;//output:3+4i; 0+0i complex output.}
C + + stream operator overloading function