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 (¶m == 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/