c++ - 关于从基类到子类指针的向下转型

标签 c++ mfc casting static-analysis effective-c++

静态检查工具显示了以下代码的违规行为:

class CSplitFrame : public CFrameWnd  
...
class CVsApp : public CWinApp
CWnd* CVsApp::GetSheetView(LPCSTR WindowText)
{
 CWnd* pWnd = reinterpret_cast<CSplitFrame*>(m_pMainWnd)->m_OutputBar.GetChildWnd(WindowText);
 return pWnd;
}

错误信息:“CSplitFrame”类继承自“CWnd”类

描述:避免向下转换继承层次。 此规则检测从基类指针到子类指针的转换。

好处:允许向下转换继承层次结构会导致维护问题,并且从基类向下转换始终是非法的。

References:

  1. Scott Meyers, "Effective C++: 50 Specific Ways to Improve Your Programs and Design", Second Edition, Addison-Wesley, (C) 2005 Pearson Education, Inc., Chapter: "Inheritance and Object-Oriented Design", Item 39
  2. JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS Chapter 4.23 Type Conversions, AV Rule 178

您认为不从基类指针向下转换为子类指针是一种好习惯吗?为什么以及何时应遵循此规则?

最佳答案

reinterpret_cast 在这里肯定是个坏主意,无论编码标准或 OOP 理论如何。它必须是 dynamic_castboost::polymorphic_downcast .

至于Effective C++的第39章,它集中讨论了必须向下转换为多种不同类型并且必须检查dynamic_cast的返回值以寻找潜在故障而导致的维护问题,从而导致多个代码中的分支:

The important thing is this: the if-then-else style of programming that downcasting invariably leads to is vastly inferior to the use of virtual functions, and you should reserve it for situations in which you truly have no alternative.

关于c++ - 关于从基类到子类指针的向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3832420/

相关文章:

c++ - shared_ptr 释放

c++ - 如何在 MFC 中禁用 CListCtrl 的水平滚动条?

c++ - Clistctrl选择检测

C : Convert Char To Float Produce 0. 000002?

c# - 转换为 int 的空对象会导致 NullReferenceException?

java - 将对象转换为类类型

c++ - Winsock 代码在 freeaddrinfo 中崩溃

c++ - 我如何使用 Qt Creator 将一个对象的值从一个窗口获取到另一个窗口的类中?

c++ - 没有 CDC 的 MFC 字符串宽度

c++ - 传递 (int x) 和 (const int &x) 之间的区别