课堂小练习: 设计、定义并实现Complex类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cmath> using namespace std; class Complex { public: Complex(double x,double y); Complex(double z); Complex(Complex &p); void add(Complex t); void show(); double mod(); private: double real,imaginary; }; Complex::Complex(double x,double y):real(x),imaginary(y) { } Complex::Complex(double z):real(z) { } Complex::Complex(Complex &p):real(p.real),imaginary(p.imaginary) { } void Complex::add(Complex t) { real=real+t.real; imaginary=imaginary+t.imaginary; } void Complex::show() { cout<<real<<"+"<<imaginary<<"i"<<endl; } double Complex::mod() { return sqrt(real*real+imaginary*imaginary); } int main() { double m; Complex c1(3,5); Complex c2(4.5); Complex c3(c1); c1.add(c2); c1.show(); m=c1.mod(); cout<<m; return 0; }
总结:
定义函数还有类的形参名对象名含糊不清,对形参变量不理解。