运算符=在C ++中重载 [英] Operator= overloading in C++

查看:152
本文介绍了运算符=在C ++中重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ Primer的书中,它有一个用于C样式字符数组的代码,并显示如何重载 = / strong>。

  String& String :: operator =(const char * sobj)
{
// sobj是空指针,
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是空指针,
if(!sobj){
_size = 0;
delete [] _string;
_string = 0;
}
else {
_size = strlen(sobj);
delete [] _string;
_string = new char [_size + 1];
strcpy(_string,sobj);
}

}




  • 请帮助。


解决方案

它支持以下成语:

 字符串a,b; 
const char * c;

//将c设置为有趣的东西

a = b = c;

为了工作, b = c 必须返回一个适当的对象或引用赋值给 a ;它实际上是 a =(b = c)根据C ++运算符优先级规则。



指针 this ,你必须写 a = *(b = c)预期意义。


In the book C++ Primer it has a code for C - style character arrays, and shows how to overload the = operator in the Article 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;
}

Now i would like to know why is there the need to return a reference String & when this code below does the same job, without any problem:

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 );
   }

}

  • please help out.

解决方案

It supports the following idiom:

String a, b;
const char *c;

// set c to something interesting

a = b = c;

For this to work, b = c must return an appropriate object or reference to assign to a; it's actually a = (b = c) according to the C++ operator precedence rules.

If you'd return the pointer this, you'd have to write a = *(b = c), which doesn't convey the intended meaning.

这篇关于运算符=在C ++中重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆