rator x = y end -----. Copy Constructing real: -1, image: -2 . //通过拷贝构造函数创建c2的一个副本返回,c2副本的值为:-1-2i Destructing real: -1, image: -2 . //析构c2的副本 Destructing real: -1, image: -2 . //析构temp3
c3 = c2 - c1; Default Constructing real: 0, image: 0 . //调用默认构造函数创建临时对象temp4,值为:0 ----- operator x - y start -----. //开始计算 c2 -c1 ,这个是调用c2的 “-” 减运算符函数 this->real: -1, this->image: -2 . //c2,通过this指针隐式地将c2传递给c2的“-”减运算符函数 other.real: 4, other.image: 4 . //c1,将c1传递给c2的“-”减运算符函数 temp.real: -5, temp.image: -6 . //相减的结果保存在临时对象temp4中,所以temp4值为:-5-6i ----- operator x - y end -----. //c2 - c1计算结束,将结果temp4返回调用处 ----- operator x = y start -----. //这里是赋值运算:c3 = temp4; 这里调用c3的“=”,过程同上 other.real: -5, other.image: -6 . this->real: 1, this->image: 2 . //赋值前c3的值为:1+2i other.real: -5, other.image: -6 . this->real: -5, this->image: -6 . //赋值后c3的值为:-5-6i ----- operator x = y end -----. Copy Constructing real: -5, image: -6 . //通过拷贝构造函数创建c3的一个副本返回,c3副本的值为:-5-6i Destructing real: -5, image: -6 . //析构c3的副本 Destructing real: -5, image: -6 . //析构temp4
c3.print(); -5-6i //经过上述计算后,打印c3的值为:-5-6i
Destructing real: -5, image: -6 . //析构c3 Destructing real: -1, image: -2 . //析构c2 Destructing real: 4, image: 4 . //析构c1 -------------------------------------------------------
从上述结果可以总结出,拷贝构造函数主要在以下3种情况下起初始化作用: 1、在声明语句中用一个对象初始化另一个对象; 2、将一个对象作为参数按值调用方式传递给另一个对象时生成对象副本; 3、生成一个临时对象作为函数的返回结果。
|