conv.h
class Base
{
public:
void foo();
};
class Derived: public Base
{
public:
void bar();
};
class A {};
class B
{
public:
void koko();
};
转换.cpp
void Base::foo()
{
cout<<"stamm";
}
void Derived::bar()
{
cout<<"bar shoudn't work"<<endl;
}
void B::koko()
{
cout<<"koko shoudn't work"<<endl;
}
主要.cpp
#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
尽管我创建了一个非派生的基类,但为什么方法 bar 在运行时被成功调用?它甚至适用于两种类型的转换(静态和重新解释转换)。
与上面相同的问题,但具有不相关的类(A 和 B)??
最佳答案
未定义的行为可以做任何事情,包括看起来有效。
关于c++ - 你能解释一下类的方法是如何调用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451003/