当一个对象超过作用域或者执行delete时,使用析构函数释放对象占有的所有资源,包括delete以及关闭所有的文件等,默认的操作是对对象的所有的成员都使用析构函数
这个函数主要定义了类对象的运算符
我们依然使用定义IntCell类来分析三大函数的使用,如果对IntCell类存有疑问可以查看本专题前几篇博客
#include<iostream>
using namespace std;
class IntCell
{
public:
explicit IntCell(int initialValue=0)
{storedValue = new int(initialValue);}
int read() const
{
return *storedValue;
}
void write(int x)
{
*storedValue = x;
}
private:
int *storedValue;
};
int main(){
IntCell a(2);
IntCell b = a;
IntCell c;
c = b;
cout<<a.read()<<endl;
a.write(4);
cout<<a.read()<<" "<<b.read()<<" "<<c.read()<<endl;
return 0;
}
#include<iostream>
using namespace std;
class IntCell
{
public:
explicit IntCell(int initialValue=0);
IntCell(const IntCell & rhs);
~IntCell();
const IntCell & operator = (const IntCell & rhs);
int read() const;
void write(int x);
private:
int *storedValue;
};
IntCell::IntCell(int initialValue)
{
storedValue = new int(initialValue);
}
IntCell::IntCell(const IntCell &rhs)
{
storedValue = new int(*rhs.storedValue);
}
IntCell::~IntCell()
{
delete storedValue;
}
const IntCell & IntCell::operator = (const IntCell & rhs)
{
if(this != &rhs)
*storedValue = *rhs.storedValue;
return *this;
}
int IntCell::read() const
{
return *storedValue;
}
void IntCell::write(int x)
{
*storedValue = x;
}
int main(){
IntCell a(2);
IntCell b = a;
IntCell c;
c = b;
cout<<a.read()<<endl;
a.write(4);
cout<<a.read()<<" "<<b.read()<<" "<<c.read()<<endl;
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容