有人能解释一下为什么下面的代码有效吗,我已经在 Visual Studio .NET 2008 上测试过它,在 Cygwin 上测试过 g++ 和 ideone.com .更重要的是我想知道它是否有效。请注意,A
和 B
是不相关的类型。
编辑:根据@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/