C和C++中的結構體:
- 在C++中允許結構體包含函數成員,甚至允許結構體中含有構造函數、重載、public/private等等(標准C不允許)。
- 在C++中,結構體和類就一個區別,默認作用域不同:在class中定義的成員默認是private,在struct默認是public。
結構體的構造函數:
自定義和默認構造函數區別可見 https://zodiac911.github.io/blog/constructor.html
當使用默認構造函數的時候對於得到的結點是隨機的,當自定義結構體時得到正確初始化的結點
TreeNode(int x) : val(x), left(NULL), right(NULL) {} 是一個構造函數,
val(x), left(NULL), right(NULL) 叫類構造函數初始化列表
1 #include <iostream> 2 using namespace std; 3 struct TreeNode { 4 int val; 5 TreeNode *left; 6 TreeNode *right; 7 //TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 }; 9 10 int main() { 11 TreeNode* node = new TreeNode; 12 cout << node->val << endl; 13 if (node->left == NULL) 14 cout << "yes" << endl; 15 return 0; 16 }
運行結果:
1 #include <iostream> 2 using namespace std; 3 struct TreeNode { 4 int val; 5 TreeNode *left; 6 TreeNode *right; 7 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 }; 9 10 int main() { 11 TreeNode* node = new TreeNode(2); 12 cout << node->val << endl; 13 if (node->left == NULL) 14 cout << "yes" << endl; 15 return 0; 16 }
運行結果: