拷贝构造函数形参规格
来源:互联网 发布:caxa编程助手2.3下载 编辑:程序博客网 时间:2024/05/16 09:57
拷贝构造函数形参规格
拷贝构造函数的形参基本都写为常量引用。
#include <iostream>using namespace std;class A{public:A(int data = 0) : m_data(data) {}~A() {}A(const A& other){m_data= other.m_data;}void print(){cout << m_data<< endl;}private:int m_data;};int main(){A a(1);A b = a;// call copy constructor (A::A(A&) or A::A(const A&))A c = 2;// call constructor and copy constructor (A::A(const A&))A d = c;// call copy constructor (A::A(A&) or A::A(const A&))const A e(3);// const objectA f = e;// call copy constructor (A::A(const A&))return 0;}main函数第一条语句调用构造函数生成一个对象。A b = a; 语句调用拷贝构造函数来生成一个对象,这里的拷贝构造函数可以使用两种形式参数引用和常量引用。
A c = 2; 由于有参数为int的构造函数,所以右端会调用这个构造函数生成一个临时变量,然后调用拷贝构造函数,由于临时变量为常量,所以这里调用的拷贝构造函数的形参必须为常量引用。
A d = c; 与A b = a; 原理相同
A f = e; 由于const变量不能转换为非const变量,所以这里调用的构造函数必须为常量引用。
总之:拷贝构造函数的形式参数中的const,是为了使用const对象来构造新对象。而其中的&则不可或缺,否则就会出现拷贝构造函数调用的递归调用。对于形参的出错情况,编译器都会给出错误。
- 拷贝构造函数形参规格
- 拷贝构造函数和无参构造函数,深浅拷贝
- 构造函数、拷贝构造函数
- 拷贝构造函数,构造函数
- 拷贝构造函数--默认拷贝构造函数
- 构造、拷贝构造函数基础
- 拷贝构造函数 深拷贝 浅拷贝
- 拷贝构造函数(深拷贝,浅拷贝)
- 拷贝构造函数浅拷贝深拷贝
- 拷贝构造函数,浅拷贝,深拷贝
- 拷贝构造函数 深拷贝 浅拷贝
- 拷贝构造函数----深拷贝、浅拷贝
- 拷贝构造函数
- 拷贝构造函数
- 浅析拷贝构造函数
- 拷贝构造函数
- 拷贝构造函数
- C++拷贝构造函数
- 图像处理模块(待补完)
- 关于PHP"=="运算符
- 深入理解JavaScript定时机制
- .Net的学习路线
- 教你怎么做才能让百度spider 更多的光谷和抓取你的网站~
- 拷贝构造函数形参规格
- Eclipse CDT 中 ** can not be resolved解决方法
- UpdatePanel中FileUpload控件获取不到值的解决办法
- 无向图的实现(邻接表) 图的遍历
- 微控制器的时钟源
- Ubuntu 12.04 amd64 搭建Apache+PHP+Mysql环境
- jQuery键盘控制方法,以及键值(keycode)对照表
- PHP中属性和方法的定义
- poj2398叉积之点定位+二分