Experience 1: manually initialize built-in objects because C ++ does not guarantee that they are initialized.
Example:
Int x = 0; // Manual initialization of int const char * text = a c-style string; // Manual initialization of the pointer double d; std :: cin> d; // The Initialization is completed by reading the input stream.
Experience 2: It is best for constructors to use the member Initial Value column (member initialization list) instead of the assignment operation in the constructor itself ). The member variables listed in the initial value column should be arranged in the same order as their declaration in class.
Example 1: Initialize with a value assignment
# Include
Using namespace std; class A {public: A () {cout <default constructor <endl ;}; A (int v): value (v ){}; A (const A & a2) {cout <copy constructor <endl;} const A & operator = (const A & lhr) const {cout <operator = <endl; return * this;} private: int value ;}; class B {public: B (A a2) {a = a2 ;}; // use the value assignment operation to initialize private: A a ;}; int main () {A a (1); B B (); // mainly through the output to see the function that defines the call of the B Variable system (pause );}
Output 1:
Copy constructor // call copy constructor of A to generate the a2 parameter for the B constructor.
Default constructor // before entering the constructor of B, call the default constructor of A to define.
Operator = // call the value assignment operator to assign a value to a2
Example 2: Use the member Initial Value column
#include
using namespace std;class A{public:A(){cout << default constructor << endl;};A(int v):value(v){};A(const A &a2){cout << copy constructor << endl;}const A& operator=(const A &lhr) const{cout << operator= << endl; return *this;}private:int value;};class B{public:B(A a2):a(a2){};private:A a;};int main(){A a(1);B b(a);system(pause);}
Output 2:
Copy constructor // call copy constructor of A to generate the a2 parameter for the B constructor.
Copy constructor // call copy constructor of A to copy a to a2