1. 程式人生 > >第三次C++實驗課

第三次C++實驗課

2.程式設計實驗用C++程式設計實現以下內容:
(1)習題4-11(教材P144)         要求:設計矩形類是,成員函式除了包括矩形面積的成員函式之外,還包括自定義建構函式、複製建構函式、解構函式。(2)習題4-20(教材P145)         基於題目要求,給出Complex類的UML類圖參考如下:
(1)#include<iostream>
using namespace std;
class Rectangle
{
public:
    Rectangle(int l,int w)
    {
        length=l;
        width=w;
    }
    float getArea()
    {
        return length*width;
    }
private:
    int length;
    int width;
};int main()
{   int length;
    cout<<"Enter the length of the rectangle:";
    cin>>length;
    int width;
    cout<<"Enter the width of the rectangle:";
    cin>>width;
    Rectangle rec(length,width);
    cout<<"The area is "<<rec.getArea()<<endl;
}(2)
#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;
}void Complex::add(Complex &c){
 r+=c.r;
 i+=c.i;
}Complex::Complex(float r1)
 {
  r=r1;
  i=0;
 }void Complex::show(){
 cout<<r<<(i>0 ? '+':'-')<<i<<'i'<<endl;
}int main()
{
 Complex c1(3,5);
 Complex c2=4.5;
 c1.add(c2);
 c1.show();
 return 0;
}
本章理解掌握的不是很好,第一題按所有要求寫程式碼編譯時出現兩個錯誤解決不了,應該是對各種函式混合使用語法掌握不到位,所以就退而求其次寫了一個不符合要求的程式碼,打算之後再參考同學程式碼修正。