我好混乱啊..析构函数..

来源:百度知道 编辑:UC知道 时间:2024/06/02 18:53:16
#include "iostream.h"

class CDog
{
public:
unsigned int m_Weight;
unsigned int m_Age;

CDog(int weight,int age);
CDog(int weight = 20);

CDog(const CDog & theDog);

void SetAge(unsigned int age);
int GetAge ();
~CDog();
};

CDog::CDog(int weight,int age)
{
m_Weight = weight;
m_Age = age;
}

CDog::CDog(int weight)
{
m_Weight = weight;
}

CDog::CDog(const CDog & theDog)
{
m_Weight = theDog.m_Weight;
m_Age = theDog.m_Age;
cout<<"copy constructor function was invoked"<<endl;
}

void CDog::SetAge(unsigned int age)
{
m_Age = age;
}

int CDog::GetAge ()
{
return m_Age;

}

CDog::~CDog()
{
cout<<"destructor function was invoked"<<endl;
}

CDog CopyData(CDog m_dog)

void test()
{
//第一次输出 destructor function was invoked 是在拷贝构造函数之后 customdog针对这个析构的
//第二个是m_dog 针对这个对像的
//第三次 是Customdog 这个对像的析构
CDog customdog(3,20);
CopyData(customdog);
}

customdog析构一次,调用CopyData的参数析构一次,因为是值拷贝,拷贝构造调用一次。