C++6ClassandObject试卷.ppt

【例4.8】复数类 Complex Complex::operator/(Complex c){ //重载/ double d=c.Real*c.Real+c.Image*c.Image ; return Complex((Real*c.Real+Image*c.Image)/d , (Image*c.Real-Real*c.Image)/d) ; } int main(void){ Complex c1(1.0,1.0) , c2(2.0,2.0) , c3(4.0,4.0) , c; double d=0.5 ; c1.Print(); c=c2+c3 ; c.Print() ; c+=c1 ; c.Print() ; c=c+d ; c.Print() ; //可用0.5代替d c=c3*c2 ; c.Print() ; c=c3/c1 ; c.Print() ; coutc3的模为:c3.abs()endl ;} c=c3=c2=c1; c.Print(); //连续赋值 c+=c3+=c2+=c1; c.Print(); //连续加赋值 return 0;} 【例4.8_1】 用友元函数重载运算符 class Complex{ double Real,Image ; public : Complex(double r=0.0, double i=0.0):Real(r),Image(i){} Complex(Complex com){ Real=com.Real ; Image=com.Image ;} void Print(){ coutReal=Real\tImage=Image\n } friend Complex operator+(const Complex ,const Complex ); friend Complex operator +=(Complex ,const Complex ); friend double abs(Complex ); friend Complex operator*(const Complex ,const Complex ); friend Complex operator/(const Complex ,const Complex ); }; 【例4.8_1】 用友元函数重载运算符 Complex operator +=(Complex c1,const Complex c2){ //重载复数+= c1.Real=c1.Real+c2.Real; c1.Image=c1.Image+c2.Image; return c1; } //返回由引用参数传递过来的变量,函数返回值可为引用 Complex operator+(const Complex c1,const Complex c2){ return Complex(c1.Real+c2.Real,c1.Image+c2.Image); } //隐式说明局部对象 Complex operator*(const Complex c1,const Complex c2){ return Complex(c1.Real*c2.Real-c1.Image*c2.Image , c1.Real*c2.Image+c2.Real*c1.Image);} Complex operator/(const Complex c1,const Complex c2){ double d=c2.Real*c2.Real+c2.Image*c2.Image ; return Complex((c1.Real*c2.Real+c1.Image*c2.Image)/d , (c1.Image*c2.Real-c1.Real*c2.Image)/d) ;} double abs(Complex c){ return sqrt(c.Real*c.Real+c.Image*c.Image);} 【例4.8_1】 用友元函数重载运算符 int main(void){ Complex c1(1.0,1.0) , c2(2.0,2.0) , c3(4.0,4.0) , c; double d=0.5 ; c1.Print(); c=c2+c3; c.Print();

文档评论(0)

1亿VIP精品文档

相关文档