简体   繁体   English

为什么从成员到派生的成员转换的指​​针给出错误

[英]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| 错误:初始化时无法将'void(Base :: )()'转换为'void(Der :: )()'|

Because your Der is not derived from Base . 因为您的Der不是从Base派生的。 Your classes are unrelated. 您的课程无关。 There's no inheritance relationship between them. 它们之间没有继承关系。

If you indeed define your Der as a descendant of Base 如果确实将Der定义为Base的后代

class Der : public Base
{
   ...

the code will compile. 代码将编译。

The compiler cannot magically guess that you wanted to derive your Der from Base . 编译器无法神奇地猜测您要从Base派生Der You are supposed to remember to explicitly tell the compiler about it. 您应该记住要明确地告诉编译器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从&#39;Derived X :: *&#39;到&#39;Base X :: *&#39;的指针到成员无效转换 - Pointer-to-Member invalid conversion from ‘Derived X::*’ to ‘Base X::*’ “指向成员的派生指针”到“指向成员的基指针”错误 - "Derived pointer to member" to "base pointer to member" error 函数在派生类中但不在基类中,指向基类的指针--&gt;“不是成员”错误 - function in derived but not in base class, pointer to base --> "not a member" error 为什么基本指针可以在虚拟函数中访问派生成员变量 - Why does a base pointer can access derived member variable in virtual funtion 错误:从派生*转换为基数& - Error: Conversion from derived* to base& 尝试通过基类指针访问派生类成员函数将导致哪种错误? - What kind of error will result from attempting to access a derived class member function through a base class pointer? 从衍生**转换为基础** - Conversion from Derived** to Base** 从基类指针访问派生类成员的设计替代方案 - Design alternative for access to derived class member from base class pointer 多态性:从基指针访问派生成员函数 - Polymorphism: Accessing derived member function from base pointer 从基类指针访问派生类成员 - Accessing derived class member from base class pointer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM