Explicit and non-explicit constructors

懵懂的女人 提交于 2019-12-12 04:43:55

问题


class Test
    {
    public:
        Test(int i) { cout<<"constructor called\n";}
        Test(const Test& t) { cout<<" copy constructor called\n";}
    };
 class Test1
        {
        public:
            Test1(int i) { cout<<"constructor called\n";}
            explicit Test1(const Test1& t) { cout<<" copy constructor called\n";}
        };

    int main()
    {
        Test t(0);  
        Test u = 0;
        //Test1 t1(0);   Line 1
        //Test1 u1 = 0;  Line 2

    }

I observe different outputs. Case 1: When Line 1 and Line 2 are commented the o/p is : constructor called constructor called

Case 2: When Line 1 and Line 2 are uncommented : then compilation error

Can someone explain the outputs and the reason for that. Also can someone tell if operator= actually ends up calling the copy constructor or not.


回答1:


Your problem lies in that explicit constructor down there, plus a slight misunderstanding of object initialization.

According to this, the expression:

Type variableName = value;

Will always perform copy initialization of such an object, that means that:

Test1 u1 = 0;

Will effectively call the overloaded constructor Test1::Test1(const Test1&), with argument Test1(int), thus resulting in u1::Test1(Test1(0)).

And, of topping, because you declare the copy constructor as explicit, the copy-style initialization will fail, but this:

Test1 t1(0);

Will compile, because this expression invokes direction initialization, and even if Test1(int) would be marked as explicit, direct initialization is explicit, so every piece matches.




回答2:


Test u = 0 is case of converting constructor. Please refer to What is a converting constructor in C++ ? What is it for? for detail .
I tried compiling commented lines after removing the comment and it compiled for me. I am using gcc version 4.3.4. Which version of compiler are you using ?



来源:https://stackoverflow.com/questions/32132268/explicit-and-non-explicit-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!