C++数据结构(三)——C++三大函数

简介

析构函数

当一个对象超过作用域或者执行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;
} 

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艾醒(AiXing-w)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值