构造函数初始化列表(4)

作用:C++提供了初始化列表语法,用来初始化属性

语法:构造函数():属性1(值1),属性2(值2)...{}

重点:体会每种写法的相通之处和区别

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //初始化列表
 5 class Person
 6 {
 7 public:
 8 
 9     //传统的初始化操作
10     /*Person(int a, int b, int c)
11     {
12         m_A = a;
13         m_B = b;
14         m_C = c;
15     }*/
16 
17     //初始化列表初始化属性操作
18     Person() :m_A(10), m_B(20), m_C(30)
19     {
20 
21     }
22 
23     //另外一种写法,无论哪种写法,结果都是一样的
24     Person(int a,int b,int c) :m_A(a), m_B(b), m_C(c)
25     {
26 
27     }
28 
29     int m_A;
30     int m_B;
31     int m_C;
32 };
33 
34 void test_01(void)
35 {
36     //传统初始化操作,创建对象时就给它赋初值
37     /*Person p(10, 20, 30);
38     cout << "m_A = " << p.m_A << endl;
39     cout << "m_B = " << p.m_B << endl;
40     cout << "m_C = " << p.m_C << endl;*/
41 
42     //初始化列表初始化属性操作
43     /*Person p;
44     cout << "m_A = " << p.m_A << endl;
45     cout << "m_B = " << p.m_B << endl;
46     cout << "m_C = " << p.m_C << endl; */
47 
48     //另外一种写法
49     Person p(30,20,10);
50     cout << "m_A = " << p.m_A << endl;
51     cout << "m_B = " << p.m_B << endl;
52     cout << "m_C = " << p.m_C << endl;
53 }
54 
55 int main(void)
56 {
57     test_01();
58 
59     system("pause");
60     return 0;
61 }

 

posted @ 2020-04-14 10:23  坦率  阅读(126)  评论(0编辑  收藏  举报