Complex 类的实现
编写复数类Complex,使得代码能够工作:
代码:
#include<iostream> #include<cmath> using namespace std; class Complex{ public: Complex(double newrl=0,double newim=0) ;//默认值不能丢。 Complex(Complex &c2); void add(Complex c2); void show(); double qumo(); private: double imaginary,real; }; Complex::Complex(double newrl,double newim){ real=newrl; imaginary=newim; } Complex::Complex(Complex &c2){ real=c2.real; imaginary=c2.imaginary;//复制函数。 } void Complex::add(Complex c) { real+=c.real; imaginary+=c.imaginary;//另一种形式的加法。 } double Complex::qumo(){ double mo; mo=sqrt(real*real+imaginary*imaginary); return mo; }//取模的实现。 void Complex::show(){ cout<<real<<"+"<<imaginary<<"i"<<endl; } int main(){ Complex c1(3,5); Complex c2(4.5); Complex c3(c1); c1.add(c2); c1.show(); c3.show(); cout<<c1.qumo()<<endl; return 0; }
图片:

类的实现需要根据实际求来做,先理清要求,再分别考虑函数的实现,最后再加以整合。对于类,如果不理解可以将它强行看做和int,double相似的类型,对比着使用,便会简单许多。
在实验的过程中我也发现了一些问题;
例如,当complex类不进行复制,使用初始值时:
做如下改动:
#include<iostream> #include<cmath> using namespace std; class Complex{ public: Complex(); Complex(double newi=0,double newr=0); Complex(Complex &p); void add(Complex p); void show(); double qumo(); private: double imaginary,real; }; Complex::Complex():imaginary(0),real(0){}//进行空值复制 Complex::Complex(double newi,double newr) { imaginary=newi; real=newr; } Complex::Complex(Complex &p){ imaginary=p.imaginary; real=p.real; } void Complex::add(Complex c) { real+=c.real; imaginary=c.imaginary; } double Complex::qumo(){ double mo; mo=sqrt(real*real+imaginary*imaginary); return mo; } void Complex::show(){ cout<<real<<"+"<<imaginary<<"i"<<endl; } int main(){ Complex c1(3,5); Complex c2(); Complex c3(c1); c1.show(); c2.show(); c3.show(); cout<<c1.qumo(); return 0; }
但运行时发现如下问题
:
44 5 C:\Users\asus\Documents\未命名1.cpp [Error] request for member 'show' in 'c2', which is of non-class type 'Complex()';
经检查发现默认值在上述代码中被两个构造函数写入,因而导致错误。。。。
We Turn Not Older With Years ,But Newer Everyday!

浙公网安备 33010602011771号