C++判断两个指针指向的对象是否相同

1、例子

class BaseA
{
public:
    int a;
};
 
class BaseB
{
public:
    double b;
};
 
class Derived : public BaseA, public BaseB
{
};
 
int main(int argc, char const *argv[])
{
    Derived derivd;
    Derived* pd = &derivd;
    BaseB* pb = &derivd;
    printf("pb = %p\n", pb);
    printf("pd = %p\n", pd);
    if (pb == pd)
    {
        printf("pb == pd\n");
    }
    else
    {
        printf("pb != pd\n");
    }
}

打印:
pb = 0028FEE0

pd = 0028FED8
pb == pd
2、结论
虽然两个指针的值不同,但是编译器认为它们还是相等的,因为它们指向同一个对象。
所以直接用if(p1 == p2)判断即可
 
 
 
 
参考:https://www.cnblogs.com/liyuan989/p/4246836.html
posted @ 2021-01-22 11:06  朱小勇  阅读(4034)  评论(0编辑  收藏  举报