c – 多态和成员函数指针如何工作?
发布时间:2020-12-16 07:05:22 所属栏目:百科 来源:网络整理
导读:参见英文答案 Pointers to virtual member functions. How does it work?????????????????????????????????????3个 我有以下代码: #include iostreamusing namespace std;class Base {public: virtual void WhoAmI() const; typedef void (Base::*WhoPtr)()
参见英文答案 >
Pointers to virtual member functions. How does it work?????????????????????????????????????3个
我有以下代码: #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行,我们从基数调用指向的函数:(theBase.* func)(). 直到现在我才明白. 之后的2行,我们从派生中调用它:( theDerived.* func)(). 它打印:我是派生的.为什么? 两个WhoAmI都是虚拟的,这意味着调用依赖于指向对象,而不是类型. 指向的对象是属于Base的func.为什么打印我是派生而不是我的基础? 解决方法
你为什么惊讶.你有一个指向成员函数的指针 指向虚拟功能.如果你拿了地址 theDerived或对它的引用,并初始化Base *或 一个基地&有了它,你期望ptrToBase-> WhoAmI()来调用 派生类中的函数.毕竟,这就是你使用的原因 一个虚拟的功能开始.当你这么做时 通过指向成员函数的指针调用.表达方式 & Base :: WhoAmI产生指向(虚拟)成员函数的指针.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |