建立复数类Complex,并且进行赋值,求和,取模等操作
1 #include "pch.h" 2 #include <iostream> 3 #include<cmath> 4 using namespace std; 5 6 class Complex 7 { 8 public: 9 Complex(double aa = 0.0, double bb = 0.0)//构造函数赋予初始值 10 { 11 a = aa; b = bb; 12 } 13 Complex(Complex &p);//赋值构造函数 14 void add(Complex x);//复数相加 15 void show();//复数输出 16 double mod();//复数取模 17 private: 18 float a; 19 float b; 20 }; 21 22 Complex::Complex(Complex &p) { 23 a = p.a; 24 b = p.b; 25 } 26 27 void Complex::add(Complex x) 28 { 29 a += x.a; 30 b += x.b; 31 } 32 33 void Complex::show() 34 { 35 cout << a << "+" << b << "i" << endl; 36 } 37 38 double Complex::mod() 39 { 40 return sqrt(a*a + b * b); 41 } 42 43 int main() 44 { 45 Complex c1(3,5); 46 cout << "c1:"; 47 c1.show(); 48 Complex c2(4.5); 49 Complex c3(c1); 50 c1.add(c2); 51 cout << endl << "c2:"; 52 c2.show(); 53 cout <<endl<< "c1+c2:"; 54 c1.show(); 55 cout << endl<< "mod(c3):"; 56 cout << c3.mod() << endl; 57 return 0; 58 }
运行结果展示:
总结体会:
通过编写这样一个简单的类,对于构造函数这一块理解更加深刻了。同时,对于OO的理解应该也有提升吧。
实验二评论地址:
1:https://www.cnblogs.com/zxz2425405395/p/10558646.html
本周事情太多,只能先评论一篇,见谅。