c++ - 不相关类型之间的 reinterpret_cast 和 virtual

标签 c++ virtual reinterpret-cast

有人能解释一下为什么下面的代码有效吗,我已经在 Visual Studio .NET 2008 上测试过它,在 Cygwin 上测试过 g++ 和 ideone.com .更重要的是我想知道它是否有效。请注意,AB 是不相关的类型。

编辑:根据@leftaroundabout 的评论,我对我的代码进行了以下更改

#include <iostream>
#include <cstdlib>

class A
{
public:
    virtual void Bar()
    {
        std::cout << "A::Bar() -> " << this << std::endl;
    }

    virtual void Foo()
    {
        std::cout << "A::Foo() -> " << this << std::endl;
    }   
};

class B
{
public:
    virtual void Foo()
    {
        std::cout << "B::Foo() -> " << this << std::endl;
    }
};

int main()
{
    B* b = reinterpret_cast<B*>( new A );
    b->Foo();   
    return EXIT_SUCCESS;
}

程序输出信息:

A::Bar() -> 0x9806008

不管调用什么,基本上第一个虚方法都会被调用。

最佳答案

它只能靠运气,标准中没有任何内容说明它应该起作用——强制转换无效。编译器可能会以完全相同的方式在内存中布置这两个类,但 AFAIK 没有这样的义务。

尝试添加:

virtual void Bar()
{
    std::cout << "A::Bar() -> " << this << std::endl;
}

A 中的 Foo 之前,看看会发生什么 - Bar 可能会在 b->Foo()< 时被调用 运行。

关于c++ - 不相关类型之间的 reinterpret_cast 和 virtual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9888102/

相关文章:

c++ - 使用reinterpret_cast 转换二进制数据在char数组中的偏移量

c++ - 以零开头的数字有什么特别之处?

c++ - 海湾合作委员会 : C++11 inline object initialization (using "this") does not work when there is a virtual inheritance in hierarchy

c++ - 当成员析构函数运行时,类具有什么类型的虚函数?

c++ - 在没有 reinterpret_cast 的情况下将 unsigned char 转换为 std::string 的方法?

c++ - 这是reinterpret_cast 的合法使用吗?如果不是,我该怎么做?

c# - Windows Phone 8 预处理器指令不适用于混合解决方案

c++ - 指针转换是否昂贵?

c++ - QThread::quit() 是立即结束线程还是等到返回事件循环?

c# - 这个。与基地。对于继承的 protected 非虚拟方法?