在 C++ Primer 一书中,它有一个 C 风格字符数组的代码,并在文章 15.3 Operator = 中展示了如何重载 =
运算符。
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 );
}
}
- 请帮忙。
最佳答案
它支持以下成语:
String a, b;
const char *c;
// set c to something interesting
a = b = c;
为此,b = c
必须返回一个适当的对象或引用以分配给 a
;根据 C++ 运算符优先级规则,它实际上是 a = (b = c)
。
如果您要返回指针 this
,则必须编写 a = *(b = c)
,这并没有传达预期的含义。
关于c++ - Operator= 在 C++ 中重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5463437/