本文介绍了为什么在这里调用Copy Constructor而不是普通的Constructor和重载的赋值运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个C类,其中重载了Normal,复制构造函数和赋值运算符,以打印出所调用内容的痕迹。I have a class C in which I have overloaded Normal, copy constructor and assignment operator to print a trace of what is being called..我编写了以下代码来测试什么时候被调用?I wrote following pieces of code to test what is being called when?C c1; --> Normal Constuctor .. // understood FineC c2;c2 = c1; --> Normal constructor + assignment operator .. //understood FineC * c3 = new C(C1) --> Copy constructor // Understood FineC c4 = c1 --> copy constructor // Not Able to understand这似乎使我感到困惑,因为尽管我正在初始化在声明时,它是通过赋值运算符而不是复制构造函数..我理解错了吗? This seems to baffle me since in this code though I am initializing at the time of declaration, it is through assignment operator and not copy constructor .. Am I understanding it wrong ?? 推荐答案因为 C c4 = c1; 在语法上在语义上等同于:Because C c4 = c1; is semantically equivalent to:C c4(c1);在这种情况下,两者都会调用拷贝构造函数。但是,复制初始化(第一种语法)和直接初始化(第二种语法)之间存在细微差别。查看此答案。Both would invoke copy constructor in this particular case. However there is a subtle difference between "copy initialization" (1st syntax) and "direct initialization" (2nd syntax). Look at this answer. 如果 C c4 = c1; ,则编译器不必检查最令人讨厌的解析。 但是,可以禁用 C c4 = c1; 一种语法,方法是声明副本构造函数 explicit 。为此,可以使任何构造函数都是显式的,并且可以防止在构造中使用 = 符号。In case of C c4 = c1;, compiler doesn't have to check for most vexing parse.However one can disable C c4 = c1; kind of syntax by declaring copy constructor explicit. For that matter any constructor can be made explicit and you can prevent = sign in the construction. 这篇关于为什么在这里调用Copy Constructor而不是普通的Constructor和重载的赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-11 17:26