Operador = sobrecarga em C ++
No livro C ++ Primer, ele possui um código para matrizes de caracteres no estilo C e mostra como sobrecarregar o=
operador no Artigo 15.3 Operador =.
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;
}
Agora eu gostaria de saber por que existe a necessidade de retornar uma referênciaString &
quando este código abaixo faz o mesmo trabalho, sem nenhum problema:
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 );
}
}
por favor ajude.