C ++-explicit

Source: Internet
Author: User

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:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.