gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:43 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com