設計、定義並實現Complex類
阿新 • • 發佈:2019-03-30
cout spa screen 默認值 ble namespace gin scree mil
實驗結論
Complex類
Code:
#include<iostream> #include<cmath> #include<cstdlib> using namespace std; class Complex { public: Complex(double newr = 0, double newi = 0); Complex(Complex &c1); void add(Complex c1); void show(); double mod(); private: double real; double imaginary; }; //構造函數 Complex::Complex(double newr/*=0*/, double newi/*=0*/) :real(newr), imaginary(newi) {} //復制構造函數 Complex::Complex(Complex &c1) : real(c1.real), imaginary(c1.imaginary) {} //復數相加 void Complex::add(Complex c1) { real += c1.real; imaginary += c1.imaginary; }//輸出 void Complex::show() { if (imaginary != 0) cout << real << "+" << imaginary << "i" << endl; else cout << real << endl; } //取模 double Complex::mod() { return sqrt(real*real + imaginary * imaginary); } int main() { Complex c1(3,5); Complex c2 = 4.5; Complex c3(c1); Complex c4; c1.add(c2); cout << "c1="; c1.show(); cout << "c2="; c2.show(); cout << "c3="; c3.show(); cout << "c4="; c4.show(); cout << "c1.mod="<<c1.mod()<<endl; system("pause"); return 0; }
Screensort:
c1為與c2相加後的值
c3為c1的初值
c4為默認值
實驗總結與體會
1.設計類時需要將所有可能出現的情況考慮在內,以此設計參數。
設計、定義並實現Complex類