C + + -- initialization list

Q: is the definition of the following program class legal? #include <iostream> using namespace std; class Test { private: const int ci; public:...

Q: is the definition of the following program class legal?

#include <iostream> using namespace std; class Test { private: const int ci; public: Test() { ci=10; } int getCi() { return ci; } }; int main() { Test t; cout<<"t="<<t<<endl; }

Result

It can be seen that the error is const defined as read-only and not initialized. After modification, the correct initialization program and result are as shown in the figure

Initialization of class members:
1.C + + provides initialization list to initialize member variables
2. Grammar rules

Matters needing attention
1. Members are initialized in the same order as members are declared
2. The initialization order of members is independent of the position in the initialization list
3. The initialization list is executed before the function body of the constructor
Code examples and results

#include <iostream> using namespace std; class Value { private: int mi; public: Value(int i) { cout<<"i="<<i<<endl;; mi = i; } int getI() { return mi; } }; class Test { private: Value m2; Value m3; Value m1; public: Test() : m1(1), m2(2), m3(3) { cout<<"Test()"<<endl; } }; int main() { Test t; return 0; }


const member in class
1. const members in the class will be allocated space
2. const members in a class are read-only variables in nature
3. const members in a class can only specify initial values in the initialization list
Code examples and results

#include <iostream> using namespace std; class Value { private: int mi; public: Value(int i) { cout<<"i="<<i<<endl; mi = i; } int getI() { return mi; } }; class Test { private: const int ci; Value m2; Value m3; Value m1; public: Test() : m1(1), m2(2), m3(3), ci(100) { cout<<"Test()"<<endl; } int getCi() { return ci; } int setCi(int v) { int* p = const_cast<int*>(&ci); *p = v; } }; int main() { Test t; cout<<"t.getCi()"<<t.getCi()<<endl; t.setCi(10); cout<<"t.getCi()"<<t.getCi()<<endl; return 0; }


We need to know that initialization and assignment are different
1. Initialization: set the initial value of the object being created
2. Assignment: set the value of the existing object
Summary
1. Initialization list can be used in class to initialize members
2. Initialization list is executed before constructor body
3. const member variables can be defined in the class
4.const member variable must specify initial value in initialization list
5.const member variable is read-only

7 November 2019, 15:57 | Views: 2845

Add new comment

For adding a comment, please log in
or create account

0 comments