c++ 重载为返回值对象以及引用的情况

来源:互联网 发布:mac safari 历史记录 编辑:程序博客网 时间:2024/06/05 10:58
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
using namespace std;
class mystring
{
public:
char *p;
int n;
mystring() :p(nullptr), n(0)
{


}
mystring(char *p)
{
this->n = strlen(p) + 1;
this->p = new char[this->n];
strcpy(this->p, p);
}
mystring(const mystring&str)
{
cout << "深拷贝" << endl;
this->n = strlen(str.p) + 1;
this->p = new char[this->n];
strcpy(this->p, str.p);
}
mystring operator+(const mystring&str)
{
cout << "赋值+重载" << endl;
mystring tmp;
tmp.n = this->n+strlen(str.p) + 1;
tmp.p = new char[tmp.n];
strcpy(tmp.p, this->p);
strcat(tmp.p, str.p);
return tmp;
}
mystring &operator=(const mystring&str)
{
cout << "赋值=重载" << endl;
char *old = str.p;
this->n =  strlen(str.p) + 1;
this->p = new char[this->n];
strcpy(this->p, str.p);
return *this;
}
~mystring()
{
delete[]p;
}
};
int main()
{
mystring str1("hello");
mystring str2("world");
mystring str3 = str1 + str2;
mystring str4(str1 + str2);
cout << str3.p << endl;
cout << str4.p << endl;
mystring str5;
str5 = str1 + str2;
cout << str5.p << endl;
cin.get();
return 0;
}
阅读全文
0 0
原创粉丝点击