C++学习(44)

 1 //可流类
 2 //把复数类设计成可流复数类
 3 #include<iostream.h>
 4 
 5 template <class T>
 6 class Complex{
 7     friend ostream & operator<<(ostream &os,Complex <T> &com);
 8     friend istream & operator>>(istream &is,Complex <T> &com);
 9     
10     private:
11         T real;
12         T image;
13     public:
14         Complex(){
15             real=0;
16             image=0;
17         }
18         Complex(T real,T image){
19             this->real=real;
20             this->image=image;
21         }
22         ~Complex(){}
23         
24         Complex operator+(const Complex &x)const{
25             return Complex(this->real+x.real,this->image+x.image);
26         }
27 };
28 
29 template <class T>
30 ostream & operator<<(ostream &os,Complex <T> &com){
31     os<<"("<<com.real<<","<<com.image<<")"<<endl;
32     return os;
33 }
34 
35 
36 template <class T>
37 istream & operator>>(istream &is,Complex <T> &com){
38     cout<<"real=";
39     is>>com.real;
40     cout<<"image=";
41     is>>com.image;
42     return is;
43 }
44 
45 
46 int main(){
47     Complex <int> a(3,5),b(2,3),c,d;
48     c=a+b;
49     cout<<"c="<<c<<endl;
50 
51     cin>>d;
52     cout<<"d="<<d<<endl;
53 
54     return 0;
55 }

猜你喜欢

转载自www.cnblogs.com/Tobi/p/9251685.html
今日推荐