我正在研究 C++ 中的 dynamic_cast
概念。
假设我们有一个 class Base
和 2 个派生类 class D1
和 class D2
,它们派生自 Base
。类 Base
有一个虚函数 fun()
。
我的问题是:
- 是否可以使用
dynamic_cast
进行向上转换和向下转换? - 如果是,哪个更受青睐和更有优势?在这方面我们可以在哪些情况下进行向下转换/向上转换?
- 是否有任何 Actor 不推荐或有害?
考虑到上述情况,请用相同的用例进行解释,以便更清楚地了解这一点。任何明确的解释都会很有帮助。
最佳答案
- 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++中处理多态对象需要做的事情。我们不能只在这里使用值。
- 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
。
- 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/