构造函数、析构函数、拷贝构造函数
来源:互联网 发布:网络技术培训 编辑:程序博客网 时间:2024/05/21 14:05
拷贝构造函数什么时候调用:
1、一个对象以值传递的方式传入函数体
2、一个对象以值传递的方式从函数返回
3、一个对象通过另一个对象进行初始化,注意,不是赋值=
<span style="font-size:18px;">#include <iostream>using namespace std;class B { public: B() { cout<<"默认构造函数"<<endl;} ~B() { cout<<"析构函数"<<n<<endl;} B(int i):data(i) //B(int) works as a converter ( int -> instance of B) { order++;n=order;cout<<"带参数的构造函数" <<n <<endl;} B(B & b){order++;n=order;data=b.data;cout<<"拷贝构造函数"<<n<<endl;}private: int data; static int order;int n;}; int B::order=0;B Play( B b) { return b ; } void main(){B t1=Play(5);cout<<"---------------------------------"<<endl;B t2=Play(t1);cout<<"--------------------------------"<<endl;}</span>
一共产生了4个对象
说明:
B t1=Play(5);
1.第一个对象是Play(5)产生的,5即B(5)
2、Play返回一个临时对象,用来初始化一个新对象,编译器优化为 B t1(Play(5));调用拷贝构造函数。
3、析构B(5);
B t2=Play(t1);
1、t1传值,调用拷贝构造函数,传入副本给函数Play
2、由于返回的对象也是用来构造一个新的对象,这是就不需要再在主程序中生成一个临时对象来接收返回值,再把临时对象的值给t2;而是直接用t2接收Play函数的返回值,即 B t2(Play(t1)); 同B t2=Play(5);
3、函数结束后,析构t1传入的副本
0 0
- 构造函数,拷贝构造函数,赋值函数,析构函数
- 构造函数,拷贝构造函数,赋值函数,析构函数
- 构造函数、析构函数、拷贝构造函数,常函数
- 构造函数、析构函数、拷贝构造函数、赋值函数
- 构造函数--拷贝构造函数--析构函数
- C++学习体会--构造函数,析构函数,拷贝构造函数
- 构造函数、析构函数、拷贝构造函数
- C++构造函数析构函数拷贝构造函数
- 构造函数,拷贝构造函数和析构函数
- C++中构造函数,拷贝构造函数,析构函数
- 构造函数,拷贝构造函数,析构函数
- 构造函数、析构函数、拷贝构造函数小结
- 构造函数、拷贝构造函数和析构函数
- c++ 构造函数,拷贝构造函数,析构函数小结
- c++ 构造函数 拷贝构造函数 析构函数 总结
- C++中的构造函数+拷贝构造函数+析构函数
- 构造函数,拷贝构造函数,析构函数
- C++ 构造函数,析构函数,拷贝构造函数
- 添加完支付宝第三方的库喜欢出错
- Java中如何利用Selenium获取元素分析网页内容
- lock类型介绍
- Spring RESTful服务接收和返回JSON最佳实践
- ServU 教程11.1.0.7使用教程
- 构造函数、析构函数、拷贝构造函数
- 位操作习题1
- 视频压缩编码和音频压缩编码的基本原理
- shell脚本显示字体颜色
- Tomcat__实现简单的登陆功能
- NAT专题
- c++ 一次完整读文件 及 实现string 的split方法
- 资源币提现方法与步骤说明
- s5pv210的汇编中断