C ++ struct
1. The C ++ struct has the default constructor.
#include
using namespace std;struct node{ int m,n;};int main(){ node a; printf("%d %d\n",a.m,a.n); return 0;}
Running result:
Because the default constructor does not have any form parameters and the function body is empty, the struct is not initialized, and the output value is given by the system. If the struct variable is defined as a global variable, the output is 0 0. This is because the initial value is different when the global variables and local variables are not initialized, resulting in different running results.
#include
using namespace std;struct node{ int m,n;};node a;int main(){ printf("%d %d\n",a.m,a.n); return 0;}
Running result:
2. After writing the default constructor, the system will not generate the default function.
# Include
Using namespace std; struct node {int m, n; node () {}// default constructor}; int main () {node; printf ("% d \ n",. m,. n); return 0 ;}
Running result:
3.
# Include
Using namespace std; struct node {int m, n; // node () {}// default constructor node (int a, int B) {n =; m = B ;}}; int main () {node a; printf ("% d \ n",. m,. n); return 0 ;}
At this time, the program fails, because a cannot find the appropriate constructor, because the default constructor system does not generate after you write the constructor. At this time, the reload constructor must be as follows:
# Include
Using namespace std; struct node {int m, n; node () {}// default constructor node (int a, int B) {n =; m = B ;}}; int main () {node a; printf ("% d \ n",. m,. n); return 0 ;}
4.
# Include
Using namespace std; struct node {int m, n; node () {}// default constructor node (int a, int B) {n =; m = B;} // use the constructor of the initialization list // node (int a, int B): m (a), n (B ){}}; int main () {node a; node B (2, 3); printf ("% d \ n",. m,. n); printf ("% d \ n", B. m, B. n); return 0 ;}
Running result:
5. Use the constructor of the initialization list
# Include
Using namespace std; struct node {int m, n; node () {}// default constructor/* node (int a, int B) {n =; m = B ;}* // use the constructor node (int a, int B) of the initialization list: m (a), n (B ){}}; int main () {node a; node B (2, 3); printf ("% d \ n",. m,. n); printf ("% d \ n", B. m, B. n); return 0 ;}
Running result: