【问题标题】:how does the ampersand(&) sign work in c++? [duplicate]&符号(&)符号如何在c ++中工作? [复制]
【发布时间】:2025-12-09 21:35:01
【问题描述】:

可能重复:
What are the differences between pointer variable and reference variable in 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 的地址。这里是什么意思?这是一种奇特的指针表示法吗?

我假设它是一个指针符号的原因是因为它毕竟是一个指针,我们正在检查两个指针​​是否相等。

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

【问题讨论】:

    标签: c++ pointers reference ampersand


    【解决方案1】:

    &amp; 有多个含义:

    1) 获取变量的地址

    int x;
    void* p = &x;
    //p will now point to x, as &x is the address of x
    

    2) 通过引用函数来传递参数

    void foo(CDummy& x);
    //you pass x by reference
    //if you modify x inside the function, the change will be applied to the original variable
    //a copy is not created for x, the original one is used
    //this is preffered for passing large objects
    //to prevent changes, pass by const reference:
    void fooconst(const CDummy& x);
    

    3) 声明一个引用变量

    int k = 0;
    int& r = k;
    //r is a reference to k
    r = 3;
    assert( k == 3 );
    

    4) 位与运算符

    int a = 3 & 1; // a = 1
    

    n) 其他人???

    【讨论】:

    • 按位
    • 问题很具体。 Q中的代码是什么意思?
    • 我不反对投反对票,但我想知道为什么这样我可以学到一些东西。
    • 我以为我很清楚,但我接受你的意见。我认为详尽的解释对他的帮助不仅仅是指出显而易见的事情。
    • @DavidHeffernan 我知道这对你来说很明显:)。我不是第一次在这里见到你:)。我的意思是我认为我很清楚他可以理解。
    【解决方案2】:

    声明为函数CDummy::isitme 的参数的CDummy&amp; param 实际上是一个reference,它“类似于”一个指针,但不同。关于引用需要注意的重要一点是,在作为参数传递的函数内部,您确实拥有对该类型实例的引用,而不是“只是”指向它的指针。因此,在注释行中,'&' 的功能就像在 C 中一样,它获取传入参数的地址,并将其与 this 进行比较,当然,this 是指向正在调用该方法的类。

    【讨论】:

      【解决方案3】:

      首先,请注意

      this
      

      是指向其所在类的特殊指针(== 内存地址)。 首先,实例化一个对象:

      CDummy a;
      

      接下来,实例化一个指针:

      CDummy *b;
      

      接下来将a的内存地址赋值给指针b

      b = &a;
      

      接下来调用CDummy::isitme(CDummy &amp;param)方法:

      b->isitme(a);
      

      在此方法中评估测试:

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

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

      这种评估通常在重载复制构造函数时进行

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

      【讨论】: