let's look at a "strange" error first: #include<iostream>#include<stdlib.h>using namespacestd;classa{Private: intsad; Public: voidF ()Const; voidF1 (); //A (int); //A ();};voidA::f ()Const{cout<<"Dfsdfds"; } voida::f1 () {cout<<"F1"; }//a::a (int sr) {//}//a::a () {} intMainintargcChar*argv[]) { ConstA CAA; caa.f (); System ("PAUSE"); return 0;} When you use the default constructor, theConstA; " Will error. But when the constructor is written out, there is no problem. Why? Well, in order to illustrate this problem, two sentences are quoted first: "The Const object must ensure that the data members of the object are not changed during their lifetime" (C++Programming thought Second Edition first volume 190 pages) "default constructor does not do any initialization work" (Money can first edition 276 pages) since the lifetime can not change, then not when the const object is created when initialization and when can initialize it? Therefore, the initialization of the data members of the object can only be done when the const object is created. But the default constructor does not do any initialization! The const object requires that it must be initialized at creation time, and the default constructor does not complete this function. With the help of user-defined constructors! And in this custom constructor, the data member must be initialized, otherwise it is not "reduced" to the level of the default constructor?! Now look at our program. When the user does not define a constructor, theConstA; "A" This object is created when the default constructor is called, but because it is const, the default constructor cannot be used, so an error is made. When the user defines the constructor "A::a () {}", although it does not (and actually should) initialize the data member, the compiler (actually the designer of the compiler) thinks it must initialize the data member in the user-defined constructor (because without this definition, it is better to use the default constructor directly. And why many times! ), so the compiler sees a user-defined constructor, thinks it initializes the data member, and gives it a line! It fooled the compiler! In this case the compilation can pass, but it is extremely undesirable. We should not play this trick of cheating the compiler, the compiler is our friend Ah.
Reprinted from: http://blog.sina.com.cn/s/blog_3c6889fe0100taud.html
Const objects and default constructor problems in C + +