本文介绍了引用派生类的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! struct Base { }; struct派生:public Base { }; void f(基数* pBase) { 派生* pDerived =(派生*)pBase; } 有没有办法让pDerived引用pBase? 解决方案 从语法上讲,是的,但我想我们应该首先确定 ,如果这真的是你需要的话。你想做什么? -Mike 我猜你写的那个演员要沉默一个编译器警告。你真的想做什么? (以上并不是你想的那样)。研究'切片''。 我正在努力让演员尽可能高效地进行演出,所以我想了 a参考会比副本快。也许我应该提到Base 是一个纯虚拟类,并且f会将pBase转换为从Base派生的多个类之一 ,具体取决于上下文。 /> 我正在尝试尽可能高效地进行演员表演, 你误解了我的问题。为什么你觉得你需要 将''Base *''转换为''Derived *''?我问,''你想要实现的是什么?',而不是''描述你是如何实现它的'' a参考会更快比副本。也许我应该提到Base 是一个纯虚拟类,f会将pBase转换为从Base派生的一些类中的一个, 但为什么呢?需要降低imo对设计的怀疑。 -Mike struct Base{};struct Derived: public Base{};void f( Base *pBase ){Derived *pDerived = (Derived*)pBase;}Is there any way to make pDerived a reference to pBase? 解决方案Syntactically, yes, but I think we should first determineif that''s really what you need. What are you trying to do?-Mike I''ll guess that you wrote that cast to silence a compiler warning. What are you really trying to do? (The above doesn''t do what you probably think). Research ''slicing''. Syntactically, yes, but I think we should first determine if that''s really what you need. What are you trying to do?I''m trying make the cast to pDerived as efficient as possible, so I figureda reference would be faster than a copy. Maybe I should mention that Baseis a pure virtual class, and f will cast pBase to one of a number of classesderived from Base, depending on context. Syntactically, yes, but I think we should first determine if that''s really what you need. What are you trying to do? I''m trying make the cast to pDerived as efficient as possible,You misunderstand my question. Why do you feel you need toconvert a ''Base *'' to a ''Derived *''? I was asking, ''what areyou trying to achieve'', not ''describe how you''re trying to achieve it'' a reference would be faster than a copy. Maybe I should mention that Base is a pure virtual class, and f will cast pBase to one of a number ofclasses derived from Base,But why? The need for downcasting imo casts much suspicion uponthe design.-Mike 这篇关于引用派生类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 09:12