c++ - 子类指针如何严格等于父类指针?

标签 c++ inheritance pointers

我在两种智能指针之间编写了一个运算符==,我想我应该运行一个快速的健全性检查。我对结果感到惊讶...

在下面的代码片段中,为什么 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/

相关文章:

c++ - 如何从该列表的元素中获取 std::list<T>::iterator?

c# - 覆盖泛型类型方法时出现编译错误

inheritance - Dart 1.13 是否放宽了 mixin 应用程序的 super 接口(interface)要求?

python - 需要 SqlAlchemy 单表继承的经典映射器示例

关于 C 中字符指针的困惑

c++ - Int 被视为 bool,& 运算符

c++ - 是否可以从 C++ 调用 Fortran 接口(interface)

c++ - Doxygen 忽略继承的函数,当类私有(private)继承但函数再次声明为公共(public)时

c - 警告 : assignment makes pointer from integer without a cast error

c - 删除 BST 中的节点而不具有指向其父节点的指针