第八週專案1(2)
阿新 • • 發佈:2019-02-18
/* *Copyright (c) 2013 ,煙臺大學計算機學院 *All rights reserved. *作者:張鳳寧 *完成日期:2014年4月16 *版本號:v1.0 *問題描述: *樣例輸入: *樣例輸出: *問題分析:用簡單的方法,學會活學活用 */ #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 &, Complex &); friend Complex operator-(Complex &, Complex &); friend Complex operator*(Complex &, Complex &); friend Complex operator/(Complex &, Complex &); friend void display(Complex &); private: double real; double imag; }; //下面定義成員函式 Complex::Complex operator+(Complex &a, Complex &b) { Complex c; c.real=a.real+b.real; c.imag=a.imag+b.imag; return c; } Complex::Complex operator-(Complex &a, Complex &b) { Complex c; c.real=a.real-b.real; c.imag=a.imag-b.imag; return c; } Complex::Complex operator*(Complex &a, Complex &b) { Complex c; c.real=a.real*b.real; c.imag=a.imag*b.imag; return c; } Complex::Complex operator/(Complex &a, Complex &b) { Complex c; c.real=a.real/b.real; c.imag=a.imag/b.imag; return c; } void display(Complex &s) { cout<<"("<<s.real<<","<<s.imag<<")"<<endl; } //下面定義用於測試的main()函式 int main() { Complex c1(3,4),c2(5,-10),c3; cout<<"c1="; display(c1); cout<<"c2="; display(c2); c3=c1+c2; cout<<"c1+c2="; display(c3); c3=c1-c2; cout<<"c1-c2="; display(c3); c3=c1*c2; cout<<"c1*c2="; display(c3); c3=c1/c2; cout<<"c1/c2="; display(c3); return 0; } 執行結果:
心得體會:友元有段時間有點不熟。