编写类String的构造函数、拷贝构造函数、析构函数和赋值函数(附代码分析解读)

本文详细解析了如何在C++中为类String编写构造函数、拷贝构造函数、析构函数以及赋值运算符函数。通过代码实例和分析,探讨了赋值运算符函数的作用,以及其与拷贝构造函数之间的区别,包括在创建新对象、调用时机和内存管理上的不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面试题:

用c++编写类的String的构造函数、拷贝构造函数、析构函数和赋值函数

具体实现代码如下:

#include<iostream>
using namespace std;
class String
{
private:
        char *p;
public:
        String(const char*p);   //普通构造函数
	String(const String& other);   //拷贝构造函数
	String& operator=(const String& other);  //赋值运算符重载函数
	~String(void);    //析构函数
	char* C_str(void) const;   //常量函数
};

String::String(const char*p)
{
	cout << "String::String(const char*p)" << endl;
	this->p = new char[strlen(p)+1];   //申请存放字符串的空间
	strcpy(this->p,p);   //用以传参
}
String::String(const String& other)
{
	cout << "String::String(const String& other)" << endl;
	this->p = new char[strlen(other.p)+1];  //自定义复制构造函数,避免指针的double free
	strcpy(this->p,other.p);
}
String& String::operator=(const String& other)
{
	cout << "operator=()is calling...." << endl;
	if(this != &other)
	{
		char *tmp=new char[strlen(other.p)+1];
		if( tm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值