- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
静态检查工具显示了以下代码的违规行为:
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:
- 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
- JOINT STRIKE FIGHTER, AIR VEHICLE, C++ CODING STANDARDS Chapter 4.23 Type Conversions, AV Rule 178
您认为不从基类指针向下转换为子类指针是一种好习惯吗?为什么以及何时应遵循此规则?
最佳答案
reinterpret_cast
在这里肯定是个坏主意,无论编码标准或 OOP 理论如何。它必须是 dynamic_cast
或 boost::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/
在Java编程中经常碰到类型转换,对象类型转换主要包括向上转型和向下转型。 向上转型 我们在现实中常常这样说:这个人会唱歌。在这里,我们并不关心这个人是黑人还是白人,是成人还是小孩,也就是说我们
当使用使用 C 风格继承的 C API 时,(利用 C 结构的标准布局),例如 GLib ,我们通常使用 C 风格的转换来向下转换: struct base_object { int x;
我是一名优秀的程序员,十分优秀!