我有以下代码:
#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
都是virtual
,这意味着调用依赖于pointed object
,而不是类型。
指向的对象是func
属于谁Base
。为什么打印I am the derived
而不是打印I am the base
?