有意思的c++題目

來源:互聯網
上載者:User

標籤:void   out   style   class   分享   str   成員變數   alt   log   

 1 #include <iostream>  2 #include<stdlib.h> 3 using namespace std;  4  5 class A  6 {  7 public:  8     int _a;  9     A() 10     { 11         _a = 1; 12     } 13     void print() 14     { 15         printf("%d\n", _a); 16     } 17 }; 18 19 class B: public A 20 { 21 public: 22     int _a; 23     B() 24     { 25         _a = 2; 26     } 27 }; 28 29 int main() 30 { 31     B b; 32     b.print(); 33     printf("%d\n", b._a); 34     return 0; 35 }

啟動並執行結果為:

子類會覆蓋父類的變數

 

 1 #include <iostream>  2 #include<stdlib.h> 3 using namespace std;  4  5 class base  6 {  7 private:  8     int m_i;  9     int m_j; 10 public: 11     base(int i):m_j(i),m_i(m_j){} 12     base():m_j(0),m_i(m_j){} 13     int get_i(){return m_i;} 14     int get_j(){return m_j;} 15 }; 16 17 int main() 18 { 19     base obj(98); 20     cout<<obj.get_i()<<endl 21         <<obj.get_j()<<endl; 22 23     return 0; 24 }

運行結果為:

建構函式的初始設定變數順序是按照成員變數的聲明順序來執行的。

 

有意思的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.