inf*_*oop 43 c++ pointers reference ampersand
可能重复:
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;
}
Run Code Online (Sandbox Code Playgroud)
在C&中通常表示var的地址.这是什么意思?这是指针符号的奇特方式吗?
我假设它的原因是一个指针表示法,因为这毕竟是一个指针,我们正在检查两个指针的相等性.
我正在从cplusplus.com学习,他们有这个例子.
Luc*_*ore 63
该&
有更多的一个含义:
1)取一个变量的地址
int x;
void* p = &x;
//p will now point to x, as &x is the address of x
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
3)声明一个引用变量
int k = 0;
int& r = k;
//r is a reference to k
r = 3;
assert( k == 3 );
Run Code Online (Sandbox Code Playgroud)
4)按位和运算符
int a = 3 & 1; // a = 1
Run Code Online (Sandbox Code Playgroud)
n)其他人???
rwo*_*ols 50
首先,请注意
this
Run Code Online (Sandbox Code Playgroud)
是一个特殊的指针(==内存地址)到它的类.首先,一个对象被实例化:
CDummy a;
Run Code Online (Sandbox Code Playgroud)
接下来,实例化一个指针:
CDummy *b;
Run Code Online (Sandbox Code Playgroud)
接下来,将内存地址a
分配给指针b
:
b = &a;
Run Code Online (Sandbox Code Playgroud)
接下来,CDummy::isitme(CDummy ¶m)
调用该方法:
b->isitme(a);
Run Code Online (Sandbox Code Playgroud)
在此方法中评估测试:
if (¶m == this) // do something
Run Code Online (Sandbox Code Playgroud)
这是棘手的部分.param是CDummy类型的对象,但是¶m
是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
}
}
Run Code Online (Sandbox Code Playgroud)
还要注意的用途*this
,其中this
被取消引用.也就是说,不是返回内存地址,而是返回位于该内存地址的对象.