调用接受基类的函数时是否需要使用dynamic_cast?
我有一些这样的类:
interface class IA
{
};
interface class IB
{
};
public ref class C : public IA, public IB
{
};
public ref class D
{
void DoSomething(IA^ aaa)
{
}
void Run()
{
C^ bob = gcnew C();
DoSomething(dynamic_cast<IA^>(bob)); // #1
DoSomething(bob); // #2
}
};
目前,我在调用这样的函数时总是尝试使用动态转换(上面的#1)。
然而它确实使代码变得相当难看,所以我想知道它是否真的有必要。
你这样使用dynamic_cast吗?如果是的话,主要原因是什么?
I have some classes like this:
interface class IA
{
};
interface class IB
{
};
public ref class C : public IA, public IB
{
};
public ref class D
{
void DoSomething(IA^ aaa)
{
}
void Run()
{
C^ bob = gcnew C();
DoSomething(dynamic_cast<IA^>(bob)); // #1
DoSomething(bob); // #2
}
};
At the moment I always try to use dynamic casting when calling such a function, (the #1 above).
However it does make the code quite ugly, so I want to know if it is actually necessary.
Do you use dynamic_cast in this way? If so what is the main reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在标准 C++ 中,您使用dynamic_cast 沿着层次结构向下走,而不是向上走。在这种情况下,您可以使用它来尝试将 IA 或 IB 转换为 C:
In standard C++, you use dynamic_cast to walk down the hierarchy, not up. In this case, you'd use it to try and convert an IA or IB into a C:
因为我们知道
bob
是C^
类型,所以我们知道在编译时它可以安全地向下转换为IA^
,所以这里的dynamic_cast
相当于static_cast
。此外,您提出的隐式强制转换也是安全的。仅当从基本类型向上转换为派生类型时才需要
dynamic_cast
。Since we know
bob
is of typeC^
, we know at compile time it can be downcasted toIA^
safely, and sodynamic_cast
is equivalent tostatic_cast
here. Moreover, the implicit cast you propose is also safe.dynamic_cast
is only needed when upcasting from a base type to a derived.不,我认为在 C++/CLI 中你也不需要这里的动态转换。 Derived* 隐式转换为 Base* ,除非多重继承存在歧义。对于“gc-pointers”来说可能也是如此。在 C++ 中,动态转换(向上转换时)需要多态类(至少具有一个虚函数)。但我不知道 C++/CLI 如何处理它。我认为每个 CLI 类默认都是多态的。
顺便说一句,您可能想删除 C++ 标签。 ;)
No, I would think that in C++/CLI you also don't need the dynamic cast here. Derived* implicitly converts to Base* unless there's an ambiguity w.r.t. multiple inheritance. The same it probably true for "gc-pointers". In C++ a dynamic cast -- when upcasting -- requires polymorphic classes (with at least one virtual function). I don't know how C++/CLI handles it, though. I would think every CLI class is by default polymorphic.
You may want to remove the C++ tag, by the way. ;)