C++学习(3)

 1 //用类实现复数的加减功能
 2 #include<iostream.h>
 3 class Complex{
 4     private:
 5         float real;//虚部
 6         float img;//实部
 7     public:
 8         Complex(float real,float img){
 9             this->real=real;
10             this->img=img;
11         }
12         Complex(){
13         }
14         Complex Add(Complex x){
15             Complex z;
16             z.real=this->real+x.real;
17             z.img=this->img+x.img;
18             return z;
19         }
20 
21         Complex Sub(Complex x){
22             Complex z;
23             z.real=this->real-x.real;
24             z.img=this->img-x.img;
25             return z;
26         }
27 
28         void Show(){
29             cout<<"real="<<this->real<<endl;
30             cout<<"img="<<this->img<<endl;
31         }
32 };
33 
34 int main(){
35     Complex x(1,1),y(2,2),z1,z2;
36     z1=x.Add(y);
37     z2=x.Sub(y);
38     z1.Show();
39     z2.Show();
40     return 0;
41 }

猜你喜欢

转载自www.cnblogs.com/Tobi/p/9244872.html