Assignment
operator= 是赋值操作的函数名,和其他函数一样有参数list和返回值
eg:
class Foo {
public:
Foo& operator=(const Foo&); // 返回是左值(left-hand object)的引用
// ...
};
//具体例子
Sales_data&
Sales_data::operator=(const Sales_data &rhs)
{
bookNo = rhs.bookNo;
units_sold = rhs.units_sold;
revenue = rhs.revenue;
return *this; // return a reference to this object
}
Destructor
对象在构造的时候系统会分配内存资源,对一些数据成员进行初始化或者赋值;一个良好的class需要有资源回收的机制,而这一操作便落在了析构函数的头上,析构函数来负责类内的资源的free
析构函数在对象生命周期结束时自动调用
析构函数执行动作是和构造函数相反的,构造函数初始化Nonstatic成员或者do other work,析构函数则是释放对象的所有资源和销毁对象的Nonstatic成员
析构函数执行动作是和构造函数相反的,构造函数先初始化成员在执行函数体,而析构函数则是在执行函数体前就已经销毁了成员
析构函数名字是类名前加符号“~”
class Foo {
public:
~Foo(); // destructor
// ...
};
看一段代码
class myclass
{
public:
myclass()
{
cout << "构造函数" << endl;
}
~myclass()
{
cout << "析构函数" << endl;
}
};
int main()
{
myclass mc;
return 0;
}
执行结果
在看下面的
int main()
{
myclass * mc;
return 0;
}
执行结果
在main主函数中,如果直接声明一个对象指针(只是声明而已),既不自动调用构造函数和析构函数。但是将main函数改为下面:
int main()
{
myclass * mc;
mc = new myclass();
return 0;
}
执行结果
这里不仅声明了一个对象指针,而且new了,这说明给这一对象指针分配一个内存空间,当然这就会调用构造函数了;咦,奇怪了。为什么不自动调用析构函数了,说明C++内部缺少这一机制,C++毫不客气的对你说:“你提醒我给一个对象分配空间,那也得麻烦你提醒我将它释放(detele)”。于是便有:
int main()
{
myclass * mc;
mc = new myclass();
delete mc;
return 0;
}
执行结果
析构函数没有参数,所以是不能重载(overloaded)的
值得一提的是C++ primer说The built-in types do not have destructors, so nothing is done to destroy members of built-in type.(内置类型无析构函数,所以在销毁时do nothing)
对于销毁指针成员,销毁的是“成员指针”而不是指针所指对象(smart point另说)
编译器自动生成的析构函数:
class Sales_data {
public:
// no work to do other than destroying the members, which happens automatically
~Sales_data() { }
// other members as before
};
注意:成员并不是在函数体内销毁,而是在函数体执行之前就已经自动销毁(这个过程是隐式(implicit)的)
对于析构函数函数体的解释:A destructor body executes in addition to the memberwise destruction that takes place as part of destroying an object.