【发布时间】:2012-04-10 21:35:28
【问题描述】:
有人能解释一下为什么下面的代码可以工作吗,我已经在 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
基本上不管调用什么,都会调用第一个虚方法。
【问题讨论】:
-
当您将
A::Foo重命名为A::Bar并保留其他所有内容时,我想它甚至“有效”?
标签: c++ virtual reinterpret-cast