我的物联网之路——C++——特殊的函数

本文介绍了C++中的复制构造函数和赋值操作符的作用及使用场景。复制构造函数用于初始化新对象时复制已有对象,而赋值操作符则在已有对象间进行数据复制。两者都需要处理指针数据成员,防止浅复制导致的问题。示例代码展示了如何自定义复制构造函数和赋值操作符以实现深复制。
摘要由CSDN通过智能技术生成
日期变更记录
2021-10-21创建

复制构造函数

下列情况,会调用复制构造函数:
将某个对象初始化为类的另一个对象时
将对象当作参数传递给函数时
函数返回对象时
为什么用复制构造函数:
如果没有定义复制构造函数,编译器将自动生成一个
自动生成的复制构造函数只是将对象内容逐个字节的copy
当数据成员有指针时,将导致两个对象的指针指向同一个地址

赋值操作符

默认的赋值操作符只是逐个字节地将源对象复制到目标对象

赋值操作符和复制构造函数

相同点:
都是为了避免在复制过程中造成的空指针问题
都需要在函数中,明确的为每一个指针开辟新的地址
都有默认的情况
不同点:
赋值操作符用的=,是在两个已存在的对象中进行数据的复制
复制构造符是创建一个新的对象

Example

复制构造函数

将某个对象初始化为类的另一个对象时自动调用复制构造函数

#if 1
#include <iostream>
#include <string.h>
using namespace std;

class stu
{
private:
	char* name;
	int age;
public:
	stu();
	stu(const char name[], int age);
	stu(const stu& s);
	~stu();
	void showName()
	{
		cout << this->name << endl;
	}
};
stu::stu()
{
	cout << "无参数的构造函数" << endl;
	this->name = new char[20];
	strcpy(name, "小明");
	age = 20;
}
stu::stu(const stu& s)
{
	cout << "复制构造函数" << endl;
	//this->name = s.name;//浅复制

	this->name = new char[20];
	strcpy(this->name,s.name);
	this->age = s.age;
}
stu::~stu()
{
	cout << "我是析构函数" << endl;
	delete[] this->name;
}
int main()
{
	stu *s1 = new stu;
	stu s2(*s1);//复制构造函数编译器默认会提供一个
	delete s1;
	return 0;
}
#endif

将对象当作参数传递给函数时自动调用复制函数


#if 1
#include <iostream>
#include <string.h>
using namespace std;
class stu
{
private:
	char* name;
	int age;
public:
	stu();
	stu(const char name[], int age);
	stu(const stu& s);
	~stu();
	void showName()
	{
		cout << this->name << endl;
	}
};
stu::stu()
{
	cout << "无参数的构造函数" << endl;
	this->name = new char[20];
	strcpy(name, "小明");
	age = 20;
}
stu::stu(const stu& s)
{
	cout << "复制构造函数" << endl;
	//this->name = s.name;//浅复制

	this->name = new char[20];
	strcpy(this->name,s.name);
	this->age = s.age;
}
stu::~stu()
{
	cout << "我是析构函数" << endl;
	delete[] this->name;
}

void  fun1(stu s)
{
	s.showName();
}
int main()
{
	stu s2;
	fun1(s2);
	return 0;
}
#endif

赋值操作符


#if 1
#include <iostream>
#include <string.h>
using namespace std;

class stu1 {
	int* ptr;
public:
	stu1() {
		ptr = new int;
		*ptr = 0;
	}
	stu1(int i)
	{
		ptr = new int;
		*ptr = i;
	}
	~stu1()
	{
		delete ptr;
	}
	void show()
	{
		cout << *ptr << endl;
	}
	stu1& operator = (const stu1& s)
		// 赋值操作符
	{
		*ptr = *(s.ptr);
		return *this;
	}
};
int main()
{
	stu1 s1(20);
	stu1 s2;
	s2 = s1;
	// 赋值操作
	s2.show();
}
#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值