问题
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