第十二週專案訓練2.2
阿新 • • 發佈:2019-01-30
/*
*Copyright(c) 2016.煙臺大學計算機與控制工程學院
*ALL rights reserved.
*檔名稱:main.cpp
*作者:王璵璠
*完成日期:2016年6月16日
問題描述:
請用類的友元函式,定義複數類過載運算子+、-、*、/,使之能用於複數的加減乘
程式:
#include<iostream> using namespace std; class Complex { public: Complex(){real=0;imag=0;} Complex(double r,double i){real=r; imag=i;} friend Complex operator+(Complex &c1,Complex &c2); friend Complex operator-(Complex &c1,Complex &c2); friend Complex operator*(Complex &c1,Complex &c2); friend Complex operator/(Complex &c1,Complex &c2); void display(); private: double real; double imag; }; //下面定義成員函式 //複數相加: (a+bi)+(c+di)=(a+c)+(b+d)i Complex operator+(Complex &c1,Complex &c2) { Complex c; c.real=c1.real+c2.real; c.imag=c1.imag+c2.imag; return c; } //複數相減: (a+bi)-(c+di)=(a-c)+(b-d)i Complex operator-(Complex &c1,Complex &c2) { Complex c; c.real=c1.real-c2.real; c.imag=c1.imag-c2.imag; return c; } //複數相乘:(a+bi)(c+di)=(ac-bd)+(bc+ad)i Complex operator*(Complex &c1,Complex &c2) { Complex c; c.real=c1.real*c2.real-c1.imag*c2.imag; c.imag=c1.imag*c2.real+c1.real*c2.imag; return c; } //複數相除:(a+bi)/(c+di)=(ac+bd)/(c*c+d*d) +(bc-ad)/(c*c+d*d)i Complex operator/(Complex &c1,Complex &c2) { Complex c; c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); return c; } void Complex::display() { cout<<"("<<real<<","<<imag<<"i)"<<endl; } //下面定義用於測試的main()函式 int main() { Complex c1(3,4),c2(5,-10),c3; cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); c3=c1+c2; cout<<"c1+c2="; c3.display(); c3=c1-c2; cout<<"c1-c2="; c3.display(); c3=c1*c2; cout<<"c1*c2="; c3.display(); c3=c1/c2; cout<<"c1/c2="; c3.display(); return 0; }
執行結果: