首页 > 解决方案 > C26434 函数 xxx 隐藏了一个非虚拟函数

问题描述

拿这个简单的代码:

void CRestoreSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
    CResizingDialog::OnSize(nType, cx, cy);

    m_gridBackupLog.ExpandLastColumn();
}

为什么会被标记?

在此处输入图像描述

C26434 函数'CRestoreSettingsDlg::OnSize'隐藏了一个非虚拟函数'CRestoreDialogDlg::OnSize'

如您所见,我调用了基类方法。


声明和定义


public:
    afx_msg void OnSize(UINT nType, int cx, int cy);

void CRestoreSettingsDlg::OnSize(UINT nType, int cx, int cy)
{
    CResizingDialog::OnSize(nType, cx, cy);

    m_gridBackupLog.ExpandLastColumn();
}

public:
    afx_msg void OnSize(UINT nType, int cx, int cy);

void CResizingDialog::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);

    Invalidate(TRUE);
}
protected:
    afx_msg void OnSize(UINT nType, int cx, int cy);

_AFXWIN_INLINE void CWnd::OnSize(UINT, int, int)
    { Default(); }

遗产

  1. class CRestoreSettingsDlg : public CResizingDialog
  2. class CResizingDialog : public CDialogEx

标签: visual-c++mfccode-inspection

解决方案


C26434 警告文档链接到C.128 C++ Core Guidelines Rule。它解释说,为了强制正确使用虚函数,非虚函数隐藏应该产生警告。

但是,对于 MFC 消息映射,您必须按照宏中指定的方式命名消息处理程序,OnSize在这种情况下,并且由于消息处理程序已经由虚拟函数(隐藏在*_MESSAGE_MAP()宏中)调度,消息处理程序本身没有是虚拟的。

因此,它可能被视为虚惊一场。或者可能被 MFC 本身视为违反上述 C.128 规则。毫不奇怪 - MFC 比这些指南早了几十年。

所以我想你可以继续为所有afx_msg功能抑制它。也许重新定义afx_msg为 include __pragma(warning(suppress(...))),或者只是在afx_msg块周围进行抑制。


一些抑制选项(Godbolt 的编译器资源管理器演示):


#define afx_msg // this is normally defined by MFC

struct base
{
    afx_msg void OnSize(){}
};


struct derived1 : base
{
    afx_msg void OnSize() {} // produces C26434
};

// Suppression by adding some code:

struct derived2 : base
{
#pragma warning(push)
#pragma warning(disable:26434)
    afx_msg void OnSize() {} 
#pragma warning(pop)
};

struct derived3 : base
{
    [[gsl::suppress(c.128)]] afx_msg void OnSize() {}
};


// Suppression by redefining MFC macro -- dirty but less intrusive:

#undef afx_msg
#define afx_msg __pragma(warning(suppress:26434))


struct derived4 : base
{
    afx_msg void OnSize() {} 
};


#undef afx_msg
#define afx_msg [[gsl::suppress(c.128)]]


struct derived5 : base
{
    afx_msg void OnSize() {}
};


推荐阅读