&符号(&)符号如何在 C++ 中工作?

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

问题描述

可能的重复:
指针变量和指针变量有什么区别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;
}

在 C &通常是指 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 I am assuming it is a pointer notation because this is a pointer after all and we are checking for equality of two pointers.

我正在 cplusplus.com 学习,他们有这个例子.

I am studying from cplusplus.com and they have this example.

推荐答案

开始,注意

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 的用法,其中this取消引用.也就是说,不是返回内存地址,而是返回位于该内存地址的对象.

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++ 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:指针和引用参数之间的区别? 下一篇:二维数组到指针的转换

相关文章

最新文章