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

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.


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

c++之Windows CE下单行EDIT控件按ENTER键时如何关闭提示音