標籤: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++結構體