c++ - Operator= 在 C++ 中重载

标签 c++ visual-c++ string operator-overloading

在 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/

相关文章:

c++ - 无法理解这个SEGFAULT

c++ - 从 debugdiag 分析时 CreateErrorInfo 上的内存泄漏?

c - 修复使用指针确定字符串长度的程序

在 R 中替换字符串的不同部分

python - 如何从字符串中修剪空格?

java - 谷歌 Protocol Buffer (Java 到 C++)

c++ - 将特定的 gcc 警告变成错误

c++ - 值如何存储在 char 中

visual-studio - 如何让 Visual Studio 将 DLL 文件复制到输出目录?

c++ - 如何按索引存储 vector 的 vector