C ++指向虚函数的指针 [英] C++ Pointer to virtual function

查看:66
本文介绍了C ++指向虚函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有这样的结构

struct A {
    void func();
};

以及类似的引用

A& a;

您可以找到指向其 func 的指针像这样的方法:

you can get a pointer to its func method like this:

someMethod(&A::func);

现在,如果该方法是虚拟的并且您不知道它在运行时是什么呢?为什么不能得到这样的指针?

Now what if that method is virtual and you don't know what it is at run-time? Why can't you get a pointer like this?

someMethod(&a.func);

是否可以找到该方法的指针?

Is it possible to get a pointer to that method?

推荐答案

指向成员的指针考虑到了它们所指向的函数的虚拟性。
例如:

Pointers to members take into account the virtuality of the functions they point at. For example:

#include <iostream>
struct Base
{
    virtual void f() { std::cout << "Base::f()" << std::endl; }
};

struct Derived:Base
{
    virtual void f() { std::cout << "Derived::f()" << std::endl; }
};


void SomeMethod(Base& object, void (Base::*ptr)())
{
    (object.*ptr)();    
}


int main()
{
    Base b;
    Derived d;
    Base* p = &b;
    SomeMethod(*p, &Base::f); //calls Base::f()
    p = &d;
    SomeMethod(*p, &Base::f); //calls Derived::f()    
}

输出:

Base::f()
Derived::f()

这篇关于C ++指向虚函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆