c++例題 建構函式(一)

來源:互聯網
上載者:User

題目來自:http://blog.csdn.net/sxhelijian/article/details/8723847

【項目1拓展(選做)】請自行設計一個矩形類,可以計算矩形的面積、周長、對象線,判斷是否是正方形。請用上類似的建構函式,自己設計main()函數,對設計的類進行測試。

#include <iostream>#include <cmath>using namespace std;class Rectangle{private:double length;double width;public:Rectangle():length(1),width(1){}Rectangle(double len,double wid):length(len),width(wid){}//   Rectangle(double len=1,double wid =1):length(len),width(wid){}double area(void);double perimeter(void){ return 2*(length+width); }double diagonal(void) { return sqrt(length*length+width*width); }bool square_or_not(void) { return length==width?true:false; }    void show_message(void);};//Rectangle::Rectangle(double len,double wid){length = len;width = wid;}double Rectangle::area(void){return length*width;}void Rectangle::show_message(void){cout << "矩形的長寬分別為: " << length << '\t' << width <<endl;cout << "周長: " << perimeter() << "面積: " << area() << "對角線長度: "<< diagonal() << endl;cout << "是否為正方形? " << square_or_not() << endl;}int main(){Rectangle rect1;rect1.show_message();Rectangle rect2(3,4);rect2.show_message();return 0;}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.