C++中的类和结构体

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 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/PennyXia/p/12759949.html