QT Basis (ii) explicit usage

Source: Internet
Author: User

recently in Review Qt, ready to do the project, QT Creator default generated code explicit Dialog (Qwidget *parent = 0), there is such a keyword Explicit , which is used to modify the constructor. In the past when writing programs under Windows, basically did not encounter this keyword, then what is the keyword to do?

the keyword Explicit can prevent the "single-argument constructor" from being used for automatic type conversions . It doesn't seem easy to see this, but here's a simple example.

//main.cpp
#include <iostream>

             using namespace std;

             class Test
             {
            public:
                 Test (int a)
                 {
                       m_data = A;
                }

                  void Show ()
                  {
                        cout << "m_data =" << m_data << Endl;
                 }

             private:
                  int m_data;
            };

void Main (void)
{
Test T = 2; Assigns a constant to an object
T.show ();
}

compile to pass, execution result: M_data = 2.

Why is that? The original C + + passed the implicit conversion, constructs a temporary object Test (2), assigns it to T (here calls the default constructor, not the overloaded "=", because this is when the object is created). Then, if the constructor is appended with the keyword explicit, the constructor becomes the explicit Test (int a) and compiles again, the compiler will error. At this point, you can only explicitly use the constructor, Test t = Test (2) .


QT Basis (ii) explicit usage

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.