显式和非显式构造函数 [英] Explicit and non-explicit constructors
问题描述
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
}
我观察到了不同的输出。
情况1:当注释第1行和第2行时,o / p为:
构造函数,称为
构造函数,称为
I observe different outputs. Case 1: When Line 1 and Line 2 are commented the o/p is : constructor called constructor called
案例2 :当第1行和第2行未注释时:则编译错误
Case 2: When Line 1 and Line 2 are uncommented : then compilation error
有人可以解释一下输出及其原因。也可以说出operator =是否实际上最终调用了副本构造函数。
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.
推荐答案
您的问题在于明确的构造函数,加上对对象初始化的一些误解。
Your problem lies in that explicit constructor down there, plus a slight misunderstanding of object initialization.
根据此,表达式:
Type variableName = value;
将始终执行 copy 初始化对象,即:
Will always perform copy initialization of such an object, that means that:
Test1 u1 = 0;
将有效地调用重载的构造函数 Test1 :: Test1(const Test1&)
,参数为 Test1(int)
,从而导致 u1 :: Test1(Test1(0))
。
Will effectively call the overloaded constructor Test1::Test1(const Test1&)
, with argument Test1(int)
, thus resulting in u1::Test1(Test1(0))
.
并且最重要的是,因为您将 copy构造函数声明为 explicit ,所以副本样式的初始化将失败,但是:
And, of topping, because you declare the copy constructor as explicit, the copy-style initialization will fail, but this:
Test1 t1(0);
将进行编译,因为此表达式将调用方向初始化,即使 Test1(int)将被标记为 explicit ,直接初始化是显式的,因此每一段都匹配。
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.
这篇关于显式和非显式构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!