1、基本概念:
- 只有一个参数,形如X::X(X&) 或X::X(const X&),二者选一
- 如果没有定义复制构造函数,那么编译器生成默认复制构造函数。默认的复制构造函数完成属性的复制功能。
- 复制构造函数只能有一个
2、没有定义复制构造函数
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class complex{
private:
double real,imag;
public:
complex(double x,double y)
{
real=x;
imag=y;
cout<<"constructor is called"<<endl;
}
void get_complex()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};
int main()
{
complex c1(1,2);
complex c2=c1;//调用默认复制构造函数,将c1的属性值拷贝赋值给c2
c2.get_complex();
}
输出结果:
constructor is called
1+2i
3、定义了自己的复制构造函数
如果定义了自己的复制构造函数,则默认的复制构造函数不存在。
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class complex{
private:
double real,imag;
public:
complex(double x,double y)
{
real=x;
imag=y;
cout<<"constructor is used"<<endl;
}
complex(complex&c)
{
real=c.real;
imag=c.imag;
cout<<"copy constuctor is called."<<endl;
}
void get_complex()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};
int main()
{
complex c1(1,2);
complex c2=c1;
c2.get_complex();
}
程序结果:
constructor is used
copy constuctor is called.
1+2i
4、复制构造函数起作用的三种情况
当用一个对象去初始化同类的另一个对象时
complex c2(c1);
complex c2=c1;//初始化语句,非赋值语句,等同于上面的一句。Remark:
如果将上面的语句改为:
complex c2;
c2=c1;//赋值语句,不是初始化语句,则不会调用赋值构造函数
。如果某函数有一个参数是类A的对象,那么该函数被调用时,类A的复制构造函数将被调用。
class complex{
private:
double real,imag;
public:
complex(double x,double y)
{
real=x;
imag=y;
cout<<"constructor is used"<<endl;
}
complex(complex&c)
{
real=c.real;
imag=c.imag;
cout<<"copy constuctor is called."<<endl;
}
void get_complex()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};
void fun(complex a)
{
}
int main()
{
complex c1(1,2);
fun(c1);
}
程序结果:
constructor is used
copy constuctor is called.
调用fun(c1)函数时,形参a用复制构造函数初始化,赋值构造函数的参数就是实参c1。此时,形参的值不一定等于实参,取决于复制构造函数。如果复制构造函数,进行了复制则形参与实参相等,否则则不相等。
- 如果函数的返回值是类A的对象,则函数返回时,A的复制构造函数被调用
class complex{
private:
double real,imag;
public:
complex(double x,double y)
{
real=x;
imag=y;
cout<<"constructor is used"<<endl;
}
complex(complex&c)
{
real=c.real;
imag=c.imag;
cout<<"copy constuctor is called."<<endl;
}
void get_complex()
{
cout<<real<<"+"<<imag<<"i"<<endl;
}
};
complex fun()
{
complex a(1,2);
return a;
}
int main()
{
fun();
}
程序结果:
constructor is used
return a;这一句执行的时候会调用复制构造函数,复制构造函数的参数为a。返回值未必与a相等,取决于复制构造函数。具体分析同上。