我在两种智能指针之间编写了一个运算符==,我想我应该运行一个快速的健全性检查。我对结果感到惊讶...
在下面的代码片段中,为什么 f 和 b 的所有变体最终都具有相同的值?
struct Foo {
int x;
};
struct Bar : public Foo {
int y;
};
#include <iostream>
int main ()
{
Bar bar;
Foo * f = &bar;
Bar * b = &bar;
std :: cout << f << " " << b << " " << (f == b) << "\n";
void * fv = f;
void * bv = b;
std :: cout << fv << " " << bv << " " << (fv == bv) << "\n";
int fi = reinterpret_cast <int> (f);
int bi = reinterpret_cast <int> (b);
std :: cout << fi << " " << bi << " " << (fi == bi) << "\n";
}
最佳答案
关于基类对象与其子类对象的地址不同的唯一情况是涉及多重继承。
在上面的例子中,内存大概是这样的:
/ --------- \ / | x | > This is the Foo portion of bar This is the whole Bar object < --------- / \ | y | \ ---------
Both views of the object have the same starting point, so a pointer to either view will have the same value.
In multiple inheritance, things get more complicated. Say you have:
struct Foo1{ int x; };
struct Foo2{ int y; };
struct Bar : public Foo1, public Foo2 { int z; };
Bar bar;
现在内存必须像这样布局:
/ --------- \ / | x | > This is the Foo1 portion of bar / --------- / \ This is the whole Bar object < | y | > This is the Foo2 portion of bar \ --------- / \ | z | \ ---------
因此 &bar
和 (Foo1*)&bar
将具有相同的值,而 (Foo2*)&bar
将具有不同的值,因为对象的 Foo2
部分从更高的地址开始。
关于c++ - 子类指针如何严格等于父类指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4307619/