简介
析构函数
当一个对象超过作用域或者执行delete时,使用析构函数释放对象占有的所有资源,包括delete以及关闭所有的文件等,默认的操作是对对象的所有的成员都使用析构函数
operator函数
这个函数主要定义了类对象的运算符
复制构造函数
在构造新的对象时,如果初始化的对象是相同类的对象的一个副本就需要用到复制构造函数。在默认情况下复制构造函数通过复制每一个数据成员来实现,对于简单的数据类型如int或double等成员不会出问题,但是数据成员是指针类型,经过复制后两个类对象就都指向了同一个地址,而我们要得到的结果是让新创建的对象有一个新的地址,只不过他们地址中存储的值不一样而已。造成这样的原因是默认情况下只是进行了浅复制(只是单纯的复制了指针变量的值,即地址),如果要实现深复制就要自己实现析构函数、operator函数和复制构造函数
例子浅析
我们依然使用定义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;
}

可以看到我们本来第二行应该输出4 2 2,现在输出的是4 4 4。
这是因为他们的指针变量都指向同一个地址
定义类以及三大函数情况分析
#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;
}

本文介绍了C++中类的三大关键函数:析构函数、operator函数和复制构造函数。析构函数用于在对象销毁时释放资源;operator函数用于自定义类对象的操作;复制构造函数则处理对象复制的情况,防止浅复制导致的问题。通过IntCell类的例子,展示了未定义这三大函数时可能导致的错误,以及定义后如何正确实现深复制。
——C++三大函数&spm=1001.2101.3001.5002&articleId=122245049&d=1&t=3&u=9f86c3484b76405eaf6ccc3b8257176e)
3744

被折叠的 条评论
为什么被折叠?



