先上代码:
class key1{ private: int _val1; }; class key2{ private: int _val2; }; class key3:public key1,public key2{ private: int _val1; }; int main(){ key3 a; key1* b = &a; key2* c = &a; key3* d = &a; cout << b <<endl<< c <<endl<< d<<endl; if (c == d){ cout << "c==d" << endl; } else cout << "c!=d" << endl; return 0; }
实现了一个简单的多继承场景
此时正常认为b和c应该是等于d的
输出结果如下:
首先我们发现,c和d的地址并不相同,这是由于受到继承的先后次序影响,导致b指向的是a中的key1部分,c指向的是a中的key2部分,而d指向的是整体的a部分(所以数值上与b相同)
那么既然不同,为什么c和d还是判等了呢?
这是因为,在做地址判等的时候,编译器会自动判断两个地址指向的是不是同一个对象,若指向的是同一的对象,就会做隐式类型转换然后判等。