设为首页 加入收藏

TOP

C++拷贝构造函数以及运算符重载例子 (Linux 下编译)(三)
2014-11-24 03:08:10 来源: 作者: 【 】 浏览:9
Tags:拷贝 构造 函数 以及 运算 重载 例子 Linux 编译
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、生成一个临时对象作为函数的返回结果


首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇PC Ubuntu下编译 Linux2.6 内核总.. 下一篇Ubuntu 10.04 内核2.6.33编译(suc..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)
·索引堆及其优化 - 菜 (2025-12-24 20:18:50)
·Shell 中各种括号的 (2025-12-24 19:50:39)
·Shell 变量 - 菜鸟教 (2025-12-24 19:50:37)