#include <iostream>
#include <cstring>
using namespace std;
class MyString
{ public:
MyString(){str=NULL;} //NULL 0
void print();
~MyString(){delete []str; }
MyString operator =(const char *);
private:
char *str;
};
void MyString::print()
{cout<<str;
}
MyString MyString::operator =(const char *r)
{ if (str) delete []str;
if (r) {str=new char[strlen(r)+1];strcpy(str,r);} else str=NULL;
return *this;
}
int main()
{ MyString s,t;
t=s="world";
s.print();
t.print();
return 0;
}
//两个输出是随机数,并且爆机
#include <iostream>
#include <cstring>
using namespace std;
class MyString
{ public:
MyString(){str=NULL;} //NULL 0
void print();
~MyString(){delete []str; }
MyString & operator =(const char *);
private:
char *str;
};
void MyString::print()
{cout<<str;
}
MyString & MyString::operator =(const char *r)
{ if (str) delete []str;
if (r) {str=new char[strlen(r)+1];strcpy(str,r);} else str=NULL;
return *this;
}
int main()
{ MyString s,t;
t=s="world";
s.print();
t.print();
return 0;
}
//两个输出是正确的,但是爆机
为什么运算符重载函数加和不加&的区别会这样
在有必须析构的类中,没有拷贝构造和拷贝赋值,会引发浅拷贝,str两次delete不崩也难。
同时,也没听说过返回值的赋值重载operator=,返回引用不会进行自身拷贝,而返回值则需要再次拷贝,然后再拷贝赋值,析构....由于又是浅拷贝所以.....多次delete....爆机。
#include <iostream>
#include <cstring>
class MyString
{
public:
MyString()
: str(nullptr) {} // NULL 0
MyString(const MyString &rhs)
{
if (rhs.str)
{
str = new char[strlen(rhs.str) + 1];
strcpy(str, rhs.str);
}
}
MyString &operator=(const MyString &rhs)
{
if (str != rhs.str)
{
if (str)
{
delete[] str;
str = nullptr;
}
if (rhs.str)
{
str = new char[strlen(rhs.str) + 1];
strcpy(str, rhs.str);
}
}
return *this;
}
MyString &operator=(const char *rhs);
~MyString() { delete[] str; }
void print();
private:
char *str = nullptr;
};
void MyString::print()
{
std::cout << str << "\n";
}
MyString &MyString::operator=(const char *rhs)
{
if (str != rhs)
{
if (str)
{
delete[] str;
str = nullptr;
}
if (rhs)
{
str = new char[strlen(rhs) + 1];
strcpy(str, rhs);
}
}
return *this;
}
int main()
{
MyString s, t;
t = s = "world";
s.print();
t.print();
return 0;
}
//两个输出是随机数,并且爆机
加了& 返回的是引用 不加 返回的是临时变量 是*this的一份拷贝