how does the ampersand(&) sign work in c++?
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
这让我困惑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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&;中,通常表示变量的地址。这里它是什么意思?这是一种奇特的指针表示法吗?
我之所以假设它是指针表示法,是因为这毕竟是一个指针,我们正在检查两个指针是否相等。
我在cplusplus.com学习,他们有这个例子。
1)获取变量的地址
1 2 3 | int x; void* p = &x; //p will now point to x, as &x is the address of x |
2)通过引用函数传递参数
1 2 3 4 5 6 7 | 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)声明引用变量
1 2 3 4 5 | int k = 0; int& r = k; //r is a reference to k r = 3; assert( k == 3 ); |
4)位与运算符
1 | int a = 3 & 1; // a = 1 |
n)其他????
首先,请注意
1 | this |
是指向其所在类的特殊指针(=memory address)。首先,对象被实例化:
1 | CDummy a; |
接下来,将实例化一个指针:
1 | CDummy *b; |
接下来,将
1 | b = &a; |
接下来,调用方法
1 | b->isitme(a); |
在此方法中评估测试:
1 | if (¶m == this) // do something |
这是棘手的部分。param是cdummy类型的对象,但
这种评估通常在重载复制构造函数时完成
1 2 3 4 5 6 7 8 | 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 } } |
还要注意
作为函数