拷贝构造函数形参规格

来源:互联网 发布: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对象来构造新对象。而其中的&则不可或缺,否则就会出现拷贝构造函数调用的递归调用。对于形参的出错情况,编译器都会给出错误。

原创粉丝点击