符号(&)符号在c ++中如何工作? [英] how does the ampersand(&) sign work in c++?

查看:132
本文介绍了符号(&)符号在c ++中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

这让我很困惑:

class CDummy 
{
public:
   int isitme (CDummy& param);
};

int CDummy::isitme (CDummy& param)
{
  if (&param == this)
  { 
       return true; //ampersand sign on left side??
  }
  else 
  {    
       return false;
  }
}

int main () 
{
  CDummy a;
  CDummy* b = &a;

  if ( b->isitme(a) )
  {
    cout << "yes, &a is b";
  }

  return 0;
}

通常表示var的地址。这是什么意思?这是一种花哨的指针表示法吗?我假设它是一个指针表示法的原因,因为这是一个指针毕竟,我们正在检查两个指针​​的相等性。
感谢。

In C & usually means the address of a var. What does it mean here? Is this a fancy way of pointer notation? The reason why i am assuming it is a pointer notation because this is a pointer after all and we are checking for equality of two pointers. Thanks.

推荐答案

要开始,请注意

this

是一个特殊的指针
首先,一个对象被实例化:

is a special pointer ( == memory address) to the class its in. First, an object is instantiated:

CDummy a;

接下来,指针被实例化:

Next, a pointer is instantiated:

CDummy *b;

接下来, a 的内存地址分配给指针 b

Next, the memory address of a is assigned to the pointer b:

b = &a;

接下来,方法 CDummy :: isitme(CDummy& param)被调用:

b->isitme(a);

在此方法内评估测试:

if (&param == this) // do something

这里是棘手的部分。 param是CDummy类型的对象,但& param 是param的内存地址。因此,param的内存地址是针对另一个名为 this 的内存地址进行测试的。如果你复制对象的内存地址,这个方法被调用到这个方法的参数中,这将导致 true

Here's the tricky part. param is an object of type CDummy, but &param is the memory address of param. So the memory address of param is tested against another memory address called "this". If you copy the memory address of the object this method is called from into the argument of this method, this will result in true.

这种评估通常在重载复制构造函数时完成。

This kind of evaluation is usually done when overloading the copy constructor

MyClass& MyClass::operator=(const MyClass &other) {
    // if a programmer tries to copy the same object into itself, protect
    // from this behavior via this route
    if (&other == this) return *this;
    else {
        // otherwise truly copy other into this
    }
}

还要注意 * this 的用法,其中正在 dereferenced 。也就是说,不返回内存地址,而是返回位于该内存地址的对象。

Also note the usage of *this, where this is being dereferenced. That is, instead of returning the memory address, return the object located at that memory address.

这篇关于符号(&amp;)符号在c ++中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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