可能的重复:
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上学习,他们有这个例子。
首先,请注意
this
是指向其所在类的特殊指针(==内存地址)。首先,实例化一个对象:
CDummy a;
接下来,实例化一个指针:
CDummy *b;
接下来,将A
的内存地址分配给指针B
:
b = &a;
接下来,调用CDummy::isitme(CDummy¶m)
方法:
b->isitme(a);
在此方法中对测试进行评估:
if (¶m == this) // do something
棘手的是。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
}
}
还要注意*this
的用法,其中this
被取消引用。也就是说,不是返回内存地址,而是返回位于该内存地址的对象。