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

标签 c++ pointers reference ampersand

Possible Duplicate:
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 学习,他们有这个例子。

最佳答案

&有多个意思:

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

关于c++ - &符号(&)符号如何在c++中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8857857/

相关文章:

c++ - 内存分配

arrays - 在 Parse 中从指针数组中检索对象,然后在 Swift 中更新 uitableview 的更有效方法

c - 如何构建一个函数,将从文件(指针)获取的数据存储在结构中?

java - 是否可以通过引用将对象从一个 Activity 传递到下一个 Activity?最佳策略是什么?

c++ - 使用引用或指针通过 xor 运算符交换两个变量的值

没有引用的Javascript克隆变量

c++ - 根据条件选择 3 个不同的 map

c++ - 使用googlemock模拟const指针参数的副作用

c++ - 寻找相似颜色的最佳颜色空间

c - C 中指向单链表指针的指针