小作业---实现String类

实现String类

题目

在这里插入图片描述

代码

#include<iostream>
using namespace std;

class String {
private:
	char* m_data;
public:
	String() {
		m_data = new char[1];
		*m_data = '\0';
		cout << "String() called " <<m_data<< endl;
	}
	String(const char *str=NULL) {
		m_data = new char[strlen(str) + 1];
		strcpy_s(m_data,strlen(str)+1,str);
		cout << "String(const char *str=NULL) called " << m_data << endl;
	}
	String(const String &other) {
		m_data = new char[strlen(other.m_data) + 1];
		strcpy_s(m_data, strlen(other.m_data) + 1,other.m_data);
		cout << "String(String &other)) called " << m_data << endl;
	}
	~String(void) {
		cout << "~String() called " << m_data << endl;
	}

	String &  operator =(const String & other) {
		if (m_data) {
			delete[] m_data;
		}
		m_data = new char[strlen(other.m_data) + 1];
		strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);
		cout << "&operator =(String & other) called " << m_data << endl;
		return *this;
	}
};
int main() {
	String s1("China");
	String s2("good");
	String s3(s1);
	String s4=s1;
	s4 = s2;
}

结果

在这里插入图片描述

注意

  1. 类中指针;
  2. s1 s2 普通构造,s3 s4 拷贝构造,s4’赋值运算符重载。
  3. 赋值操作符返回的是对象的引用。this指针。

若返回对象 执行过程如下:
1 释放对象原来的堆资源;
2 重新申请堆空间;
3 拷贝源的值到对象的堆空间的值;
4 创建临时对象(调用临时对象拷贝构造函数),将临时对象返回;
5. 临时对象结束,调用临时对象析构函数,释放临时对象堆内存

注意:如果第4步,我们没有定义拷贝构造函数,也就是没有进行深拷贝。那么在进行第5步释放临时对象的heap 空间时,将释放掉的是和目标对象同一块的heap空间。这样当目标对象B作用域结束调用析构函数时,就会产生错误!!
因此如果赋值运算符返回的是类对象本身,那么一定要重载类的拷贝构造函数(进行深拷贝)
若返回引用 执行过程如下:
1 释放对象原来的堆资源
2 重新申请堆空间
3 拷贝源的值到对象的堆空间的值
4 返回源对象的引用
5 结束。
因此,如果赋值运算符返回的是对象引用,那么其不会调用类的拷贝构造函数,这是返回对象和返回引用的主要区别,返回引用的效率明显较高.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值