C++中的&符号是如何工作的?

81

可能是重复问题:
什么是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 中,& 通常表示一个变量的地址。这里它代表什么?是指针符号的花哨写法吗?

我认为它是指针符号的写法,因为这毕竟是一个指针,我们正在比较两个指针是否相等。

我正在学习 cplusplus.com 上的示例。

3个回答

133

&有多重含义:

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) 其他人???


13
按位与。 - Andy Finkenstadt
4
问题很具体。在 Q 中的代码是什么意思? - David Heffernan
3
我不反对获得“反对票”,但我希望知道是为什么,这样我就能学到一些东西。 - Luchian Grigore
15
我认为我说得挺清楚,但我接受你的意见。我认为一番深入的解释会比单纯指出显而易见的事情对他更有帮助。 - Luchian Grigore
2
@DavidHeffernan 我知道这对你来说很明显 :). 这不是我第一次在这里看到你 :). 我的意思是,我认为我已经很清楚地让他理解了。 - Luchian Grigore
显示剩余5条评论

69

首先需要注意的是:

this

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

CDummy a;

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

CDummy *b;

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

b = &a;

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

b->isitme(a);

这个方法内部对一个测试进行了评估:

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

这里有一个棘手的部分。param是CDummy类型的一个对象,但&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解引用。也就是说,不返回内存地址,而是返回位于该内存地址上的对象。


2

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接