现在的位置: 首页 > 综合 > 正文

C++ 复制构造函数的两种用途

2013年10月13日 ⁄ 综合 ⁄ 共 555字 ⁄ 字号 评论关闭

1 利用构造函数进行类型转换

#include <iostream>

class CSample{
	int x, y;
public:
	CSample(int a, int b)
	{
		x = a;
		y = b;
		cout <<"x=" << x <<'\t' << "y = " << y << '\t' << "调用构造函数!\n";
	}
};

void main(void)
{
	CSample x1(12,105);
	x1=CSample(45,78);
}

CSample(45,78) 通过类构造函数将数据(45,78)转换为CSample类型的临时对象然后将该临时对象通过赋值语句

赋给x1,完成后,立即撤销该对象


2 复制构造函数

1)系统自动产生,当用户没有定义复制构造函数时,系统会产生一个复制构造函数

class CPoint
{
	int x, y;

public:
	CPoint(){x = 0, y = 0;};
	CPoint(int vx, int vy)
	{x = vx; y = vy;}
	void Print()
	{
		cout << x << '\t' << y << '\n';
	}
};

void main()
{
	CPoint pt1(100,200);
	CPoint pt2(pt1);

	pt1.Print();
	pt2.Print();

	system("pause");
}

2)用户自定义复制构造函数
作用:可以再自定义的复制构造函数中执行一些操作,如分配内存空间。



抱歉!评论已关闭.