gpt4 book ai didi

c++ - "upcasting"的缺点是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:30:05 34 4
gpt4 key购买 nike

抽象类的目的不是让开发人员创建基类的对象然后向上转换它,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

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

[注意 dynamic_cast<>不允许用于非多态类。]

关于c++ - "upcasting"的缺点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8047116/

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