繁体   English   中英

为什么调用错误的虚函数?

[英]Why does it call wrong virtual function?

为什么此代码调用错误的虚函数? 它在偏移量8处调用一个,而应该在偏移量4处调用一个。如果我在8处重命名该函数,它会正确地在4点处调用一个。代码生成错误? 我想念的傻事吗?

资源:

class surface_c
{
public:
    virtual ~surface_c() = 0; // 0
    virtual bool blit(int) = 0; // 4
    virtual bool blit() = 0; // 8
};

int main()
{
    surface_c* surface;
    surface->blit(0);
    return 0;
}

拆卸:

int main()
{
00A11250  push        ebp  
00A11251  mov         ebp,esp  
00A11253  sub         esp,44h  
00A11256  push        ebx  
00A11257  push        esi  
00A11258  push        edi  
    surface_c* surface;
    surface->blit(0);
00A11259  push        0  
00A1125B  mov         eax,dword ptr [surface]  
00A1125E  mov         edx,dword ptr [eax]  
00A11260  mov         ecx,dword ptr [surface]  
00A11263  mov         eax,dword ptr [edx+8]  
00A11266  call        eax  
    return 0;
00A11268  xor         eax,eax  
}
00A1126A  pop         edi  
00A1126B  pop         esi  
00A1126C  pop         ebx  
00A1126D  mov         esp,ebp  
00A1126F  pop         ebp  
00A11270  ret  
int main()
{
    surface_c* surface; // surface contains garbage, as it is uninitialzed
    surface->blit(0);
    return 0;
}

surface必须指向surface_c的某些非抽象子类,例如

surface = new surface_f();

其中surface_f是surface_c的一些非抽象子类,并且继承的纯虚函数必须由具体实现覆盖

您正在未初始化的指针上调用该方法。 幸运的是,方法被调用,程序不会崩溃。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM