complex类
#include<cmath> using namespace std; class Complex{ public:Complex(float a,float b); Complex(float n); Complex(Complex &m); void add(Complex h); void show(); float mod(); private:float real; float imaginary; }; Complex::Complex(float a,float b):real(a),imaginary(b){ } Complex::Complex(float n):real(n),imaginary(0){ } Complex::Complex(Complex &m):real(m.real),imaginary(m.imaginary){ } void Complex::add(Complex h){ real+=h.real; imaginary+=h.imaginary; } void Complex::show(){ cout<<real<<'+' <<imaginary<<'i'<<endl; } float Complex::mod(){ float s; s=sqrt(real*real+imaginary*imaginary); return s; } int main() {Complex c1(3,5); Complex c2(4.5); Complex c3(c1); c1.add(c2); c1.show(); cout<<c1.mod()<<endl; return 0; }
总结:
上课的时候没有看懂题目,只知道要有构造函数。不知道c1,c2,c3是什么。现在我知道了c1与complex的关系就像i与int的关系。
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
修改:实现c2=4.5
#include<iostream> #include<cmath> using namespace std; class Complex{ public:Complex(float a,float b); Complex(float n); Complex(const Complex &m); void add(const Complex &m); void show(); float mod(); private:float real; float imaginary; }; Complex::Complex(float a,float b):real(a),imaginary(b){ } Complex::Complex(float n):real(n),imaginary(0){ } Complex::Complex(const Complex &m):real(m.real),imaginary(m.imaginary){ } void Complex::add(const Complex &m){ real+=m.real; imaginary+=m.imaginary; } void Complex::show(){ cout<<real<<'+' <<imaginary<<'i'<<endl; } float Complex::mod(){ float s; s=sqrt(real*real+imaginary*imaginary); return s; } int main() {Complex c1(3,5); Complex c2=4.5; Complex c3(c1); c1.add(c2); c1.show(); cout<<c1.mod()<<endl; return 0; }
互评:https://www.cnblogs.com/jzgjzg
https://www.cnblogs.com/sq102217
https://www.cnblogs.com/aiwenzhuo