why does pointer to member conversion from base to derived gives error

If conversion from pointer to Base member To pointer to Derived class member is valid, why does the following code fails to compile

class Base
{
public:
    virtual void fun1()
    {
        cout<<"fun1 in Base"<<endl;
    }
};

class Der
{
public:
    void fun1()
    {
        cout<<"fun1 in Der"<<endl;
    }
};

int main()
{
    void (Der::*funptr)() = &Base::fun1;
}

Compiler gives an error saying

error: cannot convert 'void (Base::)()' to 'void (Der::)()' in initialization|


Because your Der is not derived from Base . Your classes are unrelated. There's no inheritance relationship between them.

If you indeed define your Der as a descendant of Base

class Der : public Base
{
   ...

the code will compile.

The compiler cannot magically guess that you wanted to derive your Der from Base . You are supposed to remember to explicitly tell the compiler about it.

链接地址: http://www.djcxy.com/p/23330.html

上一篇: C ++

下一篇: 为什么指向从基础到派生的成员转换会产生错误