C++ Primer Plus学习笔记之拷贝构造函数
#include<iostream>
#include<cstdlib>
using namespace std;
class Point
{
public:
Point(int ix=0,int iy=0)//创建对象,计数自增
{
x=ix;
y=iy;
PtCount++;
PrintCount("In constructor...");
}
~Point()//对象销毁,计数自减
{
PtCount--;
PrintCount("After object destroyed...");
}
static void PrintCount(const char *str)
{
cout<<str<<endl;
cout<<"Point Count="<<PtCount<<endl;
}
private:
int x;
int y;
static int PtCount;//用于对象计数
};
int Point::PtCount=0;
Point Fun(Point p)//形参p的缺省拷贝构造函数要被调用
{
Point::PrintCount("In Fun()...");
return p;
}
int main(int argc,char *argv[])
{
Point p1;
Point p2=Fun(p1);//p2的缺省拷贝构造函数要被调用
p2.PrintCount("After Point2 create...");
return 0;
}
运行结果:
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<iostream>
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<<str<<endl;
cout<<"Point Count="<<PtCount<<endl;
}
private:
int x;
int y;
static int PtCount;
};
int Point::PtCount=0;
Point Fun(Point p)
{
Point::PrintCount("In Fun()...");
return p;
}
int main(int argc,char *argv[])
{
Point p1;
Point p2=Fun(p1);
p2.PrintCount("After Point2 create...");
return 0;
}
运行结果:
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销毁
.........................................................