在书C++入门手册中,它有一个C型字符数组的代码,并说明如何在文章15.3运算符=中过载=
运算符。现在运算符= C++中的重载
String& String::operator=(const char *sobj)
{
// sobj is the null pointer,
if (! sobj) {
_size = 0;
delete[] _string;
_string = 0;
}
else {
_size = strlen(sobj);
delete[] _string;
_string = new char[ _size + 1 ];
strcpy(_string, sobj);
}
return *this;
}
我想知道为什么有需要返回参考String &
时,下面这段代码做相同的工作,没有任何问题:
void String::operator=(const char *sobj)
{
// sobj is the null pointer,
if (! sobj) {
_size = 0;
delete[] _string;
_string = 0;
}
else {
_size = strlen(sobj);
delete[] _string;
_string = new char[ _size + 1 ];
strcpy(_string, sobj);
}
}
- 请大家帮帮忙。
注意,在书中提出的解决方案是不例外安全(和这将会非常简单,我不明白他们为什么没有这样做)。 – 2011-03-28 19:15:54