/*
参数都用引用,不会调用拷贝构造。
返回引用不会调用拷贝构造。
同时,拷贝构造深拷贝,赋值重载深拷贝。
注意对象在栈上,有生命周期,拷贝栈上的对象,需要深拷贝。
*/
#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();
}
函数返回类对象的各种形式
最新推荐文章于 2023-06-22 17:40:04 发布