C++——向上转型和向下转型

标签 c++ class inheritance downcast upcasting

在我的例子中:

在向上转换时,第二个 d.print() 调用不应该打印“base”吗?

它不是“d”派生对象向上转换为基类对象吗?

而在向下转型方面,它有什么优势呢?

你能用实际的方式解释一下向上和向下吗?

#include <iostream>
using namespace std;

class Base {
public:
    void print() { cout << "base" << endl; }
};

class Derived :public Base{
public:
    void print() { cout << "derived" << endl; }

};

void main()
{
    // Upcasting
    Base *pBase;
    Derived d;
    d.print();
    pBase = &d;
    d.print();

    // Downcasting
    Derived *pDerived;
    Base *b;
    pDerived = (Derived*)b;
}

最佳答案

向上转换在 C++ 中是隐式的,在处理虚拟调度时经常使用。换句话说,您有一个指向 Base 的指针,您可以从中访问整个类层次结构的公共(public)接口(interface),并且可以在运行时进行选择。这假设您的接口(interface)函数被标记为 virtual。示例:

Base* pBase; 
cin >> x; 
if(x == 0) // this is done at runtime, as we don't know x at compile time
    pBase = new Derived1;
else
    pBase = new Derived2;

pBase->draw(); // draw is a virtual member function

在这些调度在运行时完成的情况下,它非常有用。简单地说,向上转型允许将派生类视为基类(通过其公共(public)接口(interface))。

向下转换不太有用,IMO 应该尽可能避免。一般来说,这是糟糕设计的标志,因为很少需要将 Base 对象转换为派生对象。可以通过 dynamic_cast 完成(并检查结果) , 喜欢

Base* pBase = new Derived; // OK, the dynamic type of pBase is Derived
Derived* pDerived = dynamic_cast<Derived*>(pBase);
if(pDerived) // always test  
{
    // success
}
else
{
    // fail to down-cast
}

This link提供了一个非常有用的主题介绍。

关于C++——向上转型和向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35102079/

相关文章:

java - Java获取List的具体值

python - 对 Python 类和实例变量的复合赋值

python - 实现所需的类层次结构行为的最佳方法

C# 混淆类层次结构中显式类型转换的必要性

c++ - 在 64 位机器上将 ponters 限制为 32 位

c++ - 如何在 Visual Studio 中使用 mongodb-cxx-driver 设置项目

c++ - QML 无法将 Shared_ptr<Track> 分配给 [未知属性类型]

c++ - 获取 B 值错误 : Expression must have integral or unscoped enum type

ios - 如何提供支持 UITableViewDataSource 协议(protocol)的继承 View Controller ?

c# - 在 C# 中,是否可以将 List<Child> 转换为 List<Parent>?