實驗3 類和對象
阿新 • • 發佈:2018-04-09
具體實現 .sh code 原本 alt src ret 運行 應用
實驗結論
4-11 定義並實現一個矩形類,有長,寬兩個屬性,由成員函數計算矩形的面積。
#include <iostream> using namespace std; class rectangle{ public: rectangle(float length, float wide); float area(); private: float l, w; }; rectangle::rectangle(float length, float wide){ l=length; w=wide; } float rectangle::area(){ return l*w; } int main() { float w,l; cout << "請輸入矩形的長和寬:"; cin >> l >> w; rectangle rec(l,w); float area =rec.area(); cout <<"矩形的面積是:"<<area<<endl; return 0; }
運行結果:
4-20 定義一個負數類Complex,使得下面的代碼能夠工作。
Complex c1(3,5);
Complex c2=4.5;
c1.add(c2);
c1.show();
#include <iostream> using namespace std; class Complex{ public: Complex(float r1, float i1){ //構造函數及具體實現 r=r1; i=i1; } Complex(float r1){ r=r1; i=0; } void add(Complex &C){ //復制構造函數及具體實現 r+=C.r; i+=C.i; } void show(){ cout<<r<<(i>0 ? ‘+‘:‘-‘)<<i<<‘i‘<<endl; } private: float r,i; }; int main(){ Complex c1(3,5); Complex c2=4.5; c1.add(c2); c1.show(); return 0; }
運行結果:
總結與體會
原本我對函數的構造以及實現;復制函數 理解得比較混亂,通過實例,我理解得更加深入了。
對析構函數的具體作用以及什麽時候應用仍然比較模糊。
實驗3 類和對象