c++ - 可以在 C++ 中使用 dynamic_cast 进行向上转换和向下转换

标签 c++ visual-c++ inheritance virtual dynamic-cast

我正在研究 C++ 中的 dynamic_cast 概念。

假设我们有一个 class Base 和 2 个派生类 class D1class D2,它们派生自 Base。类 Base 有一个虚函数 fun()

我的问题是:

  1. 是否可以使用 dynamic_cast 进行向上转换和向下转换?
  2. 如果是,哪个更受青睐和更有优势?在这方面我们可以在哪些情况下进行向下转换/向上转换?
  3. 是否有任何 Actor 不推荐或有害?

考虑到上述情况,请用相同的用例进行解释,以便更清楚地了解这一点。任何明确的解释都会很有帮助。

最佳答案

  1. Is upcast and downcast can both be done in dynamic_cast?

使用 dynamic_cast 进行向上转换毫无意义。 Upcast 总是会成功的。 dynamic_cast 在您不确定向下转型是否会成功时使用,因此您检查转型的结果是否成功。

假设您有一个函数 f,它接受一个 B& 并且必须决定它得到什么样的对象:

void f(B& b) {
    D1* d1 = dynamic_cast<D1*>(&b); // notice the address-of operator!
    if (d1 != nullptr)
        std::cout << "We got a D1!\n";
    else if (dynamic_cast<D2*>(&b) != nullptr) // No need to assign to a variable.
        std::cout << "We got a D2!\n";

    // Or, with a reference:
    try {
        D1& d1_ref = dynamic_cast<D1&>(b); // reference!
        std::cout << "We got a D1!\n";
    catch (std::bad_cast const&) {
        std::cout << "It was NOT a D1 after all\n";
    }
}

重要的是,以上所有代码都对指针或引用进行操作。这就是我们在C++中处理多态对象需要做的事情。我们不能只在这里使用值。

  1. If yes., Which one is more preferred and advantageous.? In which cases we can go for downcast/upcast in this regard?

在您的情况下,我们会:

D1 derived;
B& b = derived; // implicit upcast
b.fun();

static_cast<B&>(derived).fun(); // explicit upcast

// But actually, no upcast is of course needed to call `fun`:
derived.fun();

Upcast 是隐式的,你不需要为此使用任何转换。如果您明确希望将对象视为基类类型,请使用 static_cast

  1. Is any of the cast is not recommended or harmful?

见上文。如需更多信息,请阅读 cppreference entry on dynamic_cast .

关于c++ - 可以在 C++ 中使用 dynamic_cast 进行向上转换和向下转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28474895/

相关文章:

C++ malloc - 动态数组

c++ - 函数的多重声明 make 命令 UNIX

c++ - 这行代码是做什么的?玩家 = (玩家 % 2) ? 1 : 2;

c++ - 什么是 std::map<K,V>::map;以及如何知道在实现/使用 STL 容器和函数时使用什么命名空间?

c++ - 在 Linux 中获取有关进程的信息

c++ - 正确翻转/镜像图像像素?

c++ - Visual C++ 应用程序中的 SQL Server 数据库

C++ 减少冗余

C++:派生类中具有特定类型的通用基成员函数

由于父保护构造函数,C++ 无法实例化子类?