为什么答案是“OK”?
class CTest {
public:
int isitme(CTest& cobj);
};
int CTest::isitme(CTest &cobj)
{
if(&cobj == this)
{
return true;
}
else
{
return false;
}
}
int main()
{
CTest a;
CTest *b = &a;
if(b->isitme(a))
{
cout<<"OK";
}else
{
cout<<"not OK";
}
return 0;
}
最佳答案
因为成员函数隐式接收一个指向调用它的对象的指针作为参数。此指针在函数体内作为 this
指针提供。
所以当你这样做的时候:
b->isitme(a)
成员函数 isitme()
隐式 接收指针 b
作为参数,该指针将被视为 函数内部的 this
指针。
由于 b
指向 a
,this
将指向 a
(毕竟,您正在调用对象 a
上的成员函数 isitme()
通过指针 b
)。
由于 a
是作为显式参数传递的内容,因此 a
也是引用 cobj
绑定(bind)的内容。因此,获取 cobj
的地址可以得到 a
的地址。这反过来意味着,表达:
// Address of "a": "cobj" is bound to argument "a" in the function call
// vvvvv
&cobj == this
// ^^^^
// Address of "a": the function is called through a pointer to "a"
评估为 true
。
关于C++ 通过引用传递和 this 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17029831/