<分区>
我有以下代码:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void WhoAmI() const;
typedef void (Base::*WhoPtr)() const;
};
class Derived : public Base
{
public:
virtual void WhoAmI() const;
};
void Derived::WhoAmI() const
{
cout << "I am the derived" << endl;
}
void Base::WhoAmI() const
{
cout << "I am the base" << endl;
}
int main()
{
Base::WhoPtr func = &Base::WhoAmI;
Base theBase;
(theBase.*func)();
Derived theDerived;
(theDerived.*func)();
cin.get();
return 0;
}
让我们关注主要内容:
int main()
{
Base::WhoPtr func = &Base::WhoAmI;
Base theBase;
(theBase.*func)();
Derived theDerived;
(theDerived.*func)();
cin.get();
return 0;
}
我们有一个局部变量func
,它保存着Base::WhoAmI
的地址。
此外,我们还有 Base
和 Derived
对象。
在第 2 行,我们从基调用指向的 func
:(theBase.*func)()
。
我到现在才明白。
2 行之后,我们从派生调用它:(theDerived.*func)()
。
它打印:I am the derived
。为什么?
WhoAmI
都是虚拟的
,这意味着调用依赖于指向的对象
,而不是类型。
指向的对象是属于Base
的func
。为什么打印I am the derived
而不是I am the base
?