这是一个与我发布的另一个问题不同的问题,我有这段代码:
class Base
{
public:
Base()
{
};
virtual void Method()
{
cout << "Base Method";
}
};
class Derived : public Base
{
public:
virtual void Method()
{
cout << "Override Method";
}
};
class Derived2 : public Derived
{
public:
Derived2()
{
cout << "Derived2 constructor";
}
void Method()
{
cout << "Override2 Method";
}
};
int main()
{
Base *myPointer = new Derived();
dynamic_cast<Derived2*>(myPointer)->Derived2::Method();
Sleep(700);
delete myPointer;
return 0;
}
如果我写
dynamic_cast<Derived2*>(myPointer)->Method();
有一个失败(dynamic_cast 返回 NULL 并且 NULL->Method() 引发异常)这是我所期待的,但是如果我写
dynamic_cast<Derived2*>(myPointer)->Derived2::Method();
该函数甚至无需调用 Derived2 构造函数即可成功。方法甚至不是静态函数,这是怎么回事?