其他分享
首页 > 其他分享> > c – “向上转换”的缺点是什么?

c – “向上转换”的缺点是什么?

作者:互联网

抽象类的目的不是让开发人员创建基类的对象,然后再将其转换为AFAIK.

现在,即使不需要向上转换,我仍然使用它,它在某种程度上被证明是“不利的”吗?

更多说明:
来自C中的思考:

Often in a design, you want the base class to present only an
interface for its derived classes. That is, you don’t want anyone to
actually create an object of the base class, only to upcast to it so that
its interface can be used. This is accomplished by making that class
abstract,

通过向上转换,我的意思是:baseClass * obj = new derived();

解决方法:

对于非多态类,上传可能是不利的.例如:

class Fruit { ... };  // doesn't contain any virtual method
class Apple : public Fruit { ... };
class Blackberry : public Fruit { ... };

把它翻到某个地方,

Fruit *p = new Apple;  // oops, information gone

现在,如果* p是Apple或Blackberry的实例,您永远不会知道(没有任何手动机制).

[请注意,dynamic_cast<>不允许非多态类.]

标签:upcasting,c,abstract-class,virtual
来源: https://codeday.me/bug/20190826/1732642.html