Let's first look at a "strange" error:
# Include <iostream>
# Include <stdlib. h>
Using namespace STD;
Class {
PRIVATE:
Int sad;
Public:
Void F () const;
Void F1 ();
// A (INT );
// ();
};
Void A: F () const {
Cout <"dfsdfds ";
}
Void A: F1 (){
Cout <"f1 ";
}
// A: A (int sr ){
//}
// A: (){}
Int main (INT argc, char * argv [])
{
Const a caa;
CAA. F ();
System ("pause ");
Return 0;
}
When the default constructor is used, "const A;" will return an error.
However, after writing the constructor, there is no problem.
Why?
Well, to illustrate this problem, I would like to quote two sentences:
"The const object must ensure that the data members of the object are not changed during its life cycle" (C ++ programming ideology second edition first volume 190 page)
"The default constructor does not perform any initialization work" (Qian Neng's first 276 pages)
Since it cannot be changed for a lifetime, when can it be initialized when the const object is not created? Therefore, the initialization of the data member of the object can only be performed when the const object is created.
However, the default constructor does not perform any initialization! The const object must be initialized at creation, but the default constructor cannot complete this function. What should I do?
You have to use the User-Defined constructor! In addition, the data member must be initialized in this custom constructor. Otherwise, it is not "degraded" to the level of the default constructor ?!
Now let's look at our program.
When no constructor is defined, the "const A;" A is called when the object is created. However, because the object is of the const type, the default constructor cannot be used, therefore, an error is reported.
When the user defines the constructor "A: A () {}", although it does not (actually should) initialize data members, the compiler (actually the compiler designer) think that it will certainly initialize data members in user-defined Constructors (if this definition is not used, it is better to directly use the default constructor to save trouble. Why should we do it multiple times !), As soon as the compiler sees a user-defined constructor, it thinks it will initialize the data member, and it will be given a line!
It cheated the compiler!
In this case, compilation can be passed, but it is extremely undesirable. We should not play this trick to spoof the compiler. the compiler is our friend.