C ++ allows a special way to declare ratio variables. In this case, you can directly assign a value to a class variable for the data corresponding to the constructor parameter type. The compiler automatically performs class conversion during compilation and converts the data corresponding to the constructor parameter type to the class object. However, this loose rule will damage the readability of the code and lead to hard-to-find errors. In fact, if you add explicit it before the constructor, this automatic conversion will be disabled. Note that explicit only applies to constructors.
The following is an example.
#include<iostream>using namespace std;class Test{public:Test(int x=1):val(x){}int GetVal(void){return val;}private:int val;};main(){Test t1(1);cout<<"t1.val="<<t1.GetVal()<<endl;Test t2=2;cout<<"t1.val="<<t2.GetVal()<<endl;}
In the above code, we can send the number "2" directly to the test Type object T2. This is the result of implicit conversion by the C ++ compiler.
Then we add the explicit before the constructor:
#include<iostream>using namespace std;class Test{public:explicit Test(int x=1):val(x){}int GetVal(void){return val;}private:int val;};main(){Test t1(1);cout<<"t1.val="<<t1.GetVal()<<endl;Test t2=2;cout<<"t1.val="<<t2.GetVal()<<endl;}
The following error occurs during compilation: