C++ Primer Plus学习笔记之拷贝构造函数

2020-11-25 00:24

阅读:524

In constructor...

Point Count=1

In Fun()...

Point Count=1,此时已经出错了,因为此时内存中不仅存在着p1对象,还存在着临时对象形参p;

After object destroyed...

Point Count=0

After Point2 create...

Point Count=0

After object destroyed...

Point Count=-1

After object destroyed...

Point Count=-2

解决问题的方法相当直观,就是为Point类提供一个显示 的拷贝构造函数。

#include

using namespace std;

class Point
{
	public:
		Point(int ix=0,int iy=0)
		{
			x=ix;
			y=iy;
			PtCount++;
			PrintCount("In constructor...");
		}
		Point(const Point &p)//拷贝构造函数
		{
			x=p.x;
			y=p.y;
			PtCount++;
			PrintCount("In copy constructor...");
		}
		~Point()
		{
			PtCount--;
			PrintCount("After object destroyed...");
		}
		static void PrintCount(const char *str)
		{
			cout运行结果:

In constructor...

Point Count=1       p1形成

..........................................................

In copy constructor...

Point Count=2

In Fun()...

Point Count=2      形参p拷贝实参p1的结果

.........................................................

In copy constructor...

Point Count=3      p2接受Fun返回的结果

........................................................

After object destroyed...

Point Count=2      形参p销毁

........................................................

After Point2 create...

Point Count=2      p2形成

........................................................

After object destroyed...

Point Count=1      p2销毁

........................................................

After object destroyed...

Point Count=0     p1销毁

.........................................................



评论


亲,登录后才可以留言!