C++ 通过引用传递和 this 对象

标签 c++ class reference this

为什么答案是“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 指向 athis 将指向 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/

相关文章:

c++ - 集合论的取组合问题

c++ - 访问以指针类型为键的 std::map

PHP[OOP] - 如何手动调用类构造函数?

java - 如何在 Android 中获取类(非 Activity )的上下文?

php - 变量引用自身

c++ - 在 C++ 中使用 std::thread 动态创建线程

c++ - 为什么删除移动构造函数会导致 vector 停止工作

java - Scala 的类和对象的问题

c++ - 关于函数引用和线程的问题

reference - 规范问题列表