C++結構體

來源:互聯網
上載者:User

標籤:c++

1.C++結構體有預設的建構函式

#include<cstdio>using namespace std;struct node{    int m,n;};int main(){    node a;    printf("%d %d\n",a.m,a.n);    return 0;}

運行結果:

因為預設的建構函式沒有形參且函數體裡是空的,所以結構體沒有被初始化,輸出的值是系統給的,如果把結構體變數定義為全域變數,那麼會輸出0 0,這是因為全域變數和局部變數在沒有初始化時,取初值方式不同,造成運行結果不同

#include<cstdio>using namespace std;struct node{    int m,n;};node a;int main(){    printf("%d %d\n",a.m,a.n);    return 0;}

運行結果:



2.把預設的建構函式寫出來後,系統就不會再產生預設函數

#include<cstdio>using namespace std;struct node{    int m,n;    node(){}//預設的建構函式};int main(){    node a;    printf("%d %d\n",a.m,a.n);    return 0;}
運行結果:

3.

#include<cstdio>using namespace std;struct node{    int m,n;    //node(){}//預設的建構函式    node(int a,int b)    {        n=a;        m=b;    }};int main(){    node a;    printf("%d %d\n",a.m,a.n);    return 0;}

這時候程式出錯,因為a找不到合適的建構函式,因為你寫了建構函式後預設的建構函式系統就不產生了,這時候得重載建構函式如下:

#include<cstdio>using namespace std;struct node{    int m,n;    node(){}//預設的建構函式    node(int a,int b)    {        n=a;        m=b;    }};int main(){    node a;    printf("%d %d\n",a.m,a.n);    return 0;}

4.

#include<cstdio>using namespace std;struct node{    int m,n;    node(){}//預設的建構函式    node(int a,int b)    {        n=a;        m=b;    }    //使用初始化列表的建構函式    //node(int a,int b):m(a),n(b){}};int main(){    node a;    node b(2,3);    printf("%d %d\n",a.m,a.n);    printf("%d %d\n",b.m,b.n);    return 0;}

運行結果:



5.使用初始化列表的建構函式

#include<cstdio>using namespace std;struct node{    int m,n;    node(){}//預設的建構函式    /*node(int a,int b)    {        n=a;        m=b;    }*/    //使用初始化列表的建構函式    node(int a,int b):m(a),n(b){}};int main(){    node a;    node b(2,3);    printf("%d %d\n",a.m,a.n);    printf("%d %d\n",b.m,b.n);    return 0;}

運行結果:


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.