2、拷贝构造函数
拷贝构造函数是一种特殊的构造函数,其形参为本类的对象引用。实质是一种初始化对象的方法,即可以通过同一类型的其他对象初始化一个对象。当拷贝构造函数调用时,它将把已有对象的整个状态复制到相同类的新对象中。拷贝构造函数的定义及实现如下:
class 类名
{ public:
类名(形参); //构造函数声明
类名(类名 &对象名); //拷贝构造函数声明
....};
类名::类名(类名 &对象名) //拷贝构造函数具体实现
{函数体}
eg.
#include<iostream>
using namespace std;
class Ratio
{
public:
Ratio(int n=0,int d=1):num(n),den(d){}
Ratio(Ratio& r):num(r.num),den(r.den){}
void print()
{
cout << num << '/' << den;
}
private:
int num, den;
};
int main()
{
Ratio x(5, 18);
Ratio y(x);
cout << "x=";
x.print();
cout << ", y= ";
y.print();
cin.get();
}