1 #include <iostream> // 标准的输入输出
2 using namespace std;
3
4 class Person {
5 public:
6 /*
7 Person()
8 {
9 }
10
11 // 有参构造初始化
12 Person(int a, int b, int c)
13 {
14 ¦ m_A = a;
15 ¦ m_B = b;
16 ¦ m_C = c;
17 }
18 */
19 // 利用初始化列表初始化数据
20 // 构造函数后面 + :属性(参数),属性(参数)……
21 Person()
22 ¦ : m_A(10)
23 ¦ , m_B(20)
24 ¦ , m_C(30)
25 {
26 }
27
28 Person(int a, int b, int c)
29 ¦ : m_A(a)
30 ¦ , m_B(b)
31 ¦ , m_C(c)
32 {
33 }
34 int m_A;
35 int m_B;
36 int m_C;
37 };
38
39 void test01()
40 {
41 Person p1;
42 Person p2(10, 20, 30);
43 cout << "p1的m_A:" << p1.m_A << endl;
44 cout << "p1的m_B:" << p1.m_B << endl;
45 cout << "p1的m_C:" << p1.m_C << endl;
46 cout << "p2的m_A:" << p2.m_A << endl;
47 cout << "p2的m_B:" << p2.m_B << endl;
48 cout << "p2的m_C:" << p2.m_C << endl;
49 }
50 int main()
51 {
52 test01();
53 return 0;
54 }
c++ 初始化列表学习代码
最新推荐文章于 2023-11-17 12:33:40 发布