文章目录
再谈构造函数 初始化列表 类里面的成员变量都是声名 而初始化列表里面就可以对变量进行定义
1.初始化列表是成员变量定义的地方 2.const 引用 ,没有默认构造函数的自定义类型成员变量必须在初始化列表初始化,因为 初始化列表就是他们定义的地方, 3.对于像其他类型的成员变量,如int year,int month在哪里初始化都可以,影响不大,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 class Date {private : int _year; int _month; int _day; const int _N; int & _ref; A _aa; public : Date (int year, int month, int day,int i) :_year(year) , _month(month) , _day(day) ,_N(10 ) ,_ref(i) ,_aa(1 ) { } };
1 2 3 4 5 6 7 8 void initlist () { const int j = 2 ; int i = 2 ; Date s (2022 , 12 , 3 , i) ; }
explicit 1 2 3 4 5 6 7 8 9 10 11 12 13 class Date1 {public : explicit Date1 (int year) :_year(year) { }private : int _year; };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 void explicit_test () { Date1 d (2022 ) ; Date1 d2 = 2022 ; double d = 101 ; int ii = d; int * p = ⅈ int k = (int )p; string s1 ("hello world" ) ; string s2 = "hell" ; }
static 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 class B {private : int _a=0 ; static int _Scount;public : B (int a=0 ) :_a(a) ++_Scount; } B (const B&b) :_a(b._a) { ++_Scount; } static int Getcount () { return _Scount; } };int B::_Scount = 0 ;void f (B b) { }void static_test () { B b1; B b2 = 1 ; f (b1); cout << b1.Getcount () << endl; }
练习 计算1+2+……+n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 class sum {public : sum () { _ret += _i; ++_i; } static int GetRet () { return _ret; }private : static int _i; static int _ret; };int sum::_i = 1 ;int sum::_ret = 0 ;class Solution {public : int sumNums (int n) { sum a[n]; return sum::GetRet (); } };class sum {public : sum () { _ret += _i; ++_i; } static int GetRet () { return _ret; }private : static int _i; static int _ret; };int sum::_i = 1 ;int sum::_ret = 0 ;class Solution {public : int sumNums (int n) { sum a[n]; return sum::GetRet (); } };