In C + +, a class's constructor cannot directly invoke another constructor, such as:
1 #ifndef _a_h_2 #define_a_h_3#include <stdio.h>4#include <New>5 classA6 {7 Public:8 A ()9 {Tenprintf"In A::(). m_x=%d\n", m_x); OneA0); Aprintf"Out A::(). m_x=%d\n", m_x); - - } the - -Aintx) - { +printf"In A::(int x). x=%d\n", x); -m_x=x; + } A at Private: - intm_x; -};
Here the 11th line calls a (0); just constructs a temporary object, and does not call a (int x) to initialize itself. The result of the operation is:
[Email protected] utcov]#./utest. out In A::(). m_x=4268020inA::(int x). x=0outA::(). m_x=4268020
As you can see, although a (0) is called, m_x still does not change, which is 4268020.
The correct approach is to use placement NEW:
1 //A.h2 #ifndef _a_h_3 #define_a_h_4#include <stdio.h>5#include <New>6 classA7 {8 Public:9 A ()Ten { Oneprintf"In A::(). m_x=%d\n", m_x); A New( ThisA0); -printf"Out A::(). m_x=%d\n", m_x); - the } - - -Aintx) + { -printf"In A::(int x). x=%d\n", x); +m_x=x; A } at - - Private: - intm_x; - }; - in #endif
The 11th line shall be: New (This) A (0); That is, the constructor a (int x) is called with the current object to construct a "new" object. The result of the operation is:
[Email protected] utcov]#./utest. out In A::(). m_x=4268020in A::(int x). x=0out A::(). m_x=0
As you can see, the current object is indeed changed.
"Go" How to call another constructor in a constructor in C + +