您好,欢迎来到欧得旅游网。
搜索
您的当前位置:首页C++数据结构(三)——C++三大函数

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

来源:欧得旅游网

简介

析构函数

当一个对象超过作用域或者执行delete时,使用析构函数释放对象占有的所有资源,包括delete以及关闭所有的文件等,默认的操作是对对象的所有的成员都使用析构函数

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;
} 

定义类以及三大函数情况分析

#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;
} 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- ovod.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务