【實驗3】類與對象

//4-11
//
定義一個矩形類,有長寬兩個屬性,由成員函數計算矩形的面積 #include<iostream> using namespace std; //定義類 rectangle class rectangle{ public: //公共成員接口 rectangle(double l,double w); //構造函數 rectangle(rectangle &R0); //複製構造函數 ~rectangle(); //析構函數 double area(double length,double width){ return length*width; }; //計算矩形面積,內聯函數 private: //私有成員接口 double length; double width; }; // 構造函數初始化數據成員 rectangle::rectangle(double l,double w){ length = l; width = w; } //複製析構函數初始化數據成員 rectangle::rectangle(rectangle &R0){ length = R0.length; width = R0.width; } //實現析構函數 rectangle::~rectangle() { } //主函數 int main(){ double length,width; cout << "enter the length of the rectangle :" ; cin >> length; cout << "enter the width of the rectangle :"; cin >> width; rectangle R1(length,width); //定義rectangle類的對象R1 cout << "the area of the rectangle is :" << R1.area(length,width) << endl; return 0; }

運行截圖:ios

 

//4-20 
//定義一個複數類 

#include<iostream>
using namespace std;
class Complex{
    public:
        Complex(float r1,float i1);  
        Complex(float r1);
        void add(Complex &c);
        void show();
 
    private:
        float r;
        float i;
    };
    
//構造函數初始化 
Complex::Complex(float r1,float i1){
    r=r1;
    i=i1;
}

//add函數 
void Complex::add(Complex &c){
    r+=c.r;
    i+=c.i;
}

//show函數 
void Complex::show(){
    cout<<r<<(i>0 ? '+':'-')<<i<<'i'<<endl;
}

//構造函數初始化 
Complex::Complex(float r1){
    r=r1;
    i=0;
}

//主函數 
int main(){
    Complex c1(3,5);   //用複數3+5i初始化c1 
    Complex c2=4.5;    //用實數4,5初始化c2 
    c1.add(c2);        //將c1與c2相加,結果保存在c1中 
    c1.show();         //輸出c1 
    return 0;
}

運行截圖:函數

 

 

關於知識點的總結,見【知識點總結】博客。spa

相關文章
相關標籤/搜索