转换.h
class Base
{
public:
void foo();
};
class Derived: public Base
{
public:
void bar();
};
class A {};
class B
{
public:
void koko();
};
转化率
void Base::foo()
{
cout<<"stamm";
}
void Derived::bar()
{
cout<<"bar shoudn't work"<<endl;
}
void B::koko()
{
cout<<"koko shoudn't work"<<endl;
}
主文件
#include "conv.h"
#include <iostream>
int main()
{
Base * a = new Base;
Derived * b = static_cast<Derived*>(a);
b->bar();
Derived * c = reinterpret_cast<Derived*>(a);
c->bar();
A* s1 = new A;
B* s2 = reinterpret_cast<B*>(s1);
s2->koko();
}
输出:
bar shoudn't work
bar shoudn't work
koko shoudn't work
尽管我创建了一个未派生的基类,但如何在运行时成功调用方法栏?它甚至适用于两种类型的转换(静态和重新解释转换)。
与上述相同的问题,但与不相关的类(A 和 B)?