函数返回类对象的各种形式

/*
	参数都用引用,不会调用拷贝构造。
	返回引用不会调用拷贝构造。
	同时,拷贝构造深拷贝,赋值重载深拷贝。
	注意对象在栈上,有生命周期,拷贝栈上的对象,需要深拷贝。
*/
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>

using namespace std;

class MyString
{
public:
	char *p;
	int size;
	MyString() :size(0),p(nullptr)
	{
		cout << "call MyString1" << endl;
	}
	MyString(char *str)
	{
		cout << "call MyString2" << endl;
		p = new char[strlen(str) + 1];
		size = strlen(str) + 1;
		strcpy(p, str);
	}
	//MyString(MyString &my)	//拷贝构造基于引用构造 ,浅拷贝
	//{
	//	cout << "call 浅拷贝" << endl;
	//	this->p = my.p;
	//	this->size = my.size;
	//}
	MyString(MyString & my)	//深拷贝
	{
		cout << "call 深拷贝" << endl;
		this->size = my.size;
		this->p = new char[this->size];
		strcpy(this->p, my.p);  //副本机制,返回值会调用拷贝构造

	}

	//加法重载 
	MyString operator +(MyString &my)
	{
		MyString temp; //自动消亡,会调用析构函。
		temp.size = this->size + my.size;
		temp.p = new char[temp.size];
		strcpy(temp.p, this->p);
		strcat(temp.p, my.p);
		return temp;
	}
	void operator =(MyString &my)
	{
		cout << "赋值重载" << endl;
		this->size = my.size;
		this->p = new char[this->size];
		strcpy(this->p, my.p);
	}

	~MyString()
	{
		cout << "call delete" << endl;
		delete[] p;
	}
};

void main()
{
	MyString str1("123");
	//MyString str1 = "123";
	MyString str2 = "abc";
	 
	MyString temp = str1 + str2;
	//MyString temp = str1 + str2;分步解析 其中 “=”:为赋值重载
	//1:MyString temp:会调用构造
	//2:str1+str2:会调用重载(+)
	//3:重载时又有返回值,会调用拷由构造,因为拷贝构造有个临时对象所以有个栈的消亡
	cout << temp.p << endl;

	MyString temp2;
	temp2 = str1 + str2; //赋值重载,这时赋值重载也必须深拷贝...
	//重载 :void operator =(MyString &my)函数。
	cout << temp2.p << "  " << temp2.size << endl;

	/*
	1:MyString temp = str1 + str2;  //先赋值重载,再拷贝构造
	2:MyString temp;
	temp = str1 + str2;		//赋值重载
	
	*/


	cin.get();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值