C++學習之建構函式和解構函式

來源:互聯網
上載者:User

標籤:

 1 /* 2  3  4   實驗啟示1:構造子類對象時,先調用父類建構函式,後調用子類建構函式 5   實驗啟示2:析構子類對象時,先調用子類解構函式,後調用父類解構函式 6   實驗啟示3:在這個對象生命週期結束時,解構函式會自動調用 7  8  9  */10 11 #include<iostream>12 13 int flag;14 15 class Animal16 {17 18 public:19 20     int weight;21     int length;22     double hungry_rate;23 24     Animal(void);25     ~Animal(){flag++;std::cout<<flag<<". I‘m ~Animal(),now."<<std::endl;}26 27     void eat(void);28 29 };30 31 Animal::Animal()32 {33     flag++;34 35     std::cout<<flag<<". I‘m Animal,now."<<std::endl;36 37     weight=25;38     Animal::length=10;39     Animal::hungry_rate=70;40 41 }42 43 void Animal::eat(void)44 {45 46     std::cout<<"The Animal is eating"<<std::endl;47 48 }49 50 class Fish:public Animal51 {52 53 public:54 55     Fish(){ flag++;std::cout<<flag<<". I‘m Fish,now."<<std::endl;}56     ~Fish(){flag++;std::cout<<flag<<". I‘m ~Fish(),now."<<std::endl;}57 58     void swim()59     {60 61         std::cout<<"The Fish Is Swimming!"<<std::endl;62 63     }64 };65 66 int main()67 {68 69     Fish x;70 71     x.eat();72 73     std::cout<<x.hungry_rate;74 75     x.swim();76 77     return 0;78 }

運行結果:

C++學習之建構函式和解構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.