67

可能重复:
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 学习,他们有这个例子。

4

3 回答 3

110

具有更多的&含义:

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

于 2012-01-13T22:06:29.270 回答
62

首先,请注意

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还要注意, where thisis being dereferenced的用法。也就是说,不是返回内存地址,而是返回位于该内存地址的对象。

于 2012-01-13T22:25:05.493 回答
2

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

于 2012-01-13T22:10:43.050 回答