本文介绍了为什么我不能投射一个指针Derived类的成员函数到相同但是类Base?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,将 void(Derived :: *)()转换为 void(Base :: *) ),如下面的代码所示:

To me it looks perfectly safe to cast a void(Derived::*)() to a void(Base::*)(), like in this code:

#include <iostream>
#include <typeinfo>
using namespace std;
struct Base{
    void(Base::*any_method)();
    void call_it(){
        (this->*any_method)();
    }
};
struct Derived: public Base{
    void a_method(){
        cout<<"method!"<<endl;
    }
};
int main(){
    Base& a=*new Derived;
    a.any_method=&Derived::a_method;
    a.call_it();
}

但是编译器抱怨 any_method =& Derived :: a_method; 。这是一个路障,以防止微妙的编程错误,或只是一些让生活更容易编译器作家?是否有解决方法让 Base 类具有指向 Derived 的成员函数的指针,不带类型knoweledge (即,我不能使 Base 具有模板参数 Derived 的模板)。

But the compiler complains about the cast at a.any_method=&Derived::a_method;. Is this a roadblock to prevent subtle programming errors, or just something to make life easier for compiler writers? Are there workarounds to let the Base class have a pointer to member functions of Derived without type knoweledge (that is, I cannot make Base a template with template argument Derived).

推荐答案

如果你的 Derived :: a_method()试图使用一个数据成员在 Derived 中,而不是在 Base ,并且在 Base object(或从 Base 派生但与 Derived 无关的对象)?

What happens if your Derived::a_method() attempts to use a data member only present in Derived, not in Base, and you call it on a Base object (or an object derived from Base but not related to Derived)?

换句话说,换句话说是有意义的,这个不是。

The conversion the other way around makes sense, this one doesn't.

这篇关于为什么我不能投射一个指针Derived类的成员函数到相同但是类Base?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 01:46