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
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html