据我了解,要传递/返回多态对象,您需要使用指针或引用类型来防止切片问题。但是,要从函数返回对象,您不能在堆栈上创建并返回引用,因为本地对象将不再存在。如果您在堆上创建并返回引用/指针-调用者必须管理内存-不好。考虑到上述情况,我将如何编写一个返回多态类型的函数?我会使用什么返回机制/类型? 最佳答案 您将返回一个负责内存管理并明确所有权的智能指针:#includestructIFoo{virtual~IFoo(){}};structFoo1:IFoo{};structFoo2:IFoo{};std::unique_ptrmake_f
我很难解决这个问题。假设我有这个vectorstd::vector>cars;Car是一个抽象类。我希望能够返回不同类型的弱指针,所以我执行以下操作。templatestd::weak_ptrGetCar(){for(std::vector>::iteratorit=cars.begin();it!=cars.end();++it){T*derived=dynamic_cast((*it).get());if(derived!=nullptr){std::weak_ptrcarPointer=*it;returncarPointer;}}returnstd::weak_ptr();}但
我有一些代码需要优化。它看起来像这样:functionabc(stringformat){if(format=="a"){//thisisastring,Ishouldn'thaveusedsinglequote,sorryfortheconfusionclassx::at;doit(t);}if(format=="b"){classx::bt;doit(t);}if(format=="c"){classx::ct;doit(t)}if(format=="d"){classx::dt;doit(t);}}目前有很多不同类型的doit()函数functiondoit(classx:a){
关闭。这个问题需要更多focused.它目前不接受答案。想改进这个问题吗?更新问题,使其只关注一个问题editingthispost.关闭6年前。Improvethisquestion我有一个关于OOP概念的愚蠢问题,我们选择多态性的原因是什么??C++中的简单代码:classShape{public:virtualvoiddraw(){coutdraw();deleteptr;return7;}这里ptr->draw()函数会调用Triangle绘制,如果指向Rectangle则调用Rectangle绘制,这是后期绑定(bind)。创建基类指针并将其指向不同类的必要性是什么?我们可以
我有一个基类,我希望它看起来像这样:classB{//shouldlooklike:intI(){returnsomeConst;}virtualintI()=0;publicB(){something(I());}}重点是强制派生类重写I并强制在构造每个对象时调用它。这用于做一些簿记,我需要知道正在构造什么类型的对象(但我将当前对象视为基类)。这行不通,因为C++不允许您从构造函数调用抽象虚函数。有没有办法达到同样的效果?基于thislink答案似乎是没有办法得到我想要的。然而它说的是:Theshortansweris:no.Abaseclassdoesn'tknowanything
我有一个C++库,它使用这样的对象层次结构:classA{...}classB:publicA{...}classC:publicA{...}我通过typedef和函数通过CAPI公开功能,如下所示:#ifdef__cplusplustypedefA*APtr;#elsetypedefstructA*APtr;#endifextern"C"voidsome_function(APtrobj);但是,假设使用CAPI执行如下操作:BPtrb=bptr_create();some_function((APtr)b);这是多态有效的,因为B扩展了A,并且我的API依赖于可能实现的此类功能,但
我正在尝试通过初始化列表初始化指向类A的指针集合。但是,初始化列表不能使用引用作为模板类型。我有以下代码。#include#include#include#include#include#includestructA{virtualvoidf()constnoexcept{std::cout>vec;public:Test(conststd::initializer_list&list)//Test(conststd::initializer_list&list)(x));}voidprint(){std::for_each(vec.begin(),vec.end(),[](autox
考虑以下代码:#include#include#includeusingnamespacestd;structA{intdata;};structB1:A{};structB2:virtualA{};structBase1:virtualA{};structBase2:virtualA{};structDerived:Base1,Base2{};intmain(){cout::value::value::value在我的系统上打印4812000这意味着这些类都不是多态的。但是,B1和B2的大小因指针的确切大小而异,该指针可能是指向vtable的指针。我用-fdump-class-hie
我正在使用RESTAPI接收数据。数据模型是多态相关的,类似于文档中的模型:https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relationspostsid-integertitle-stringbody-textvideosid-integertitle-stringurl-stringcommentsid-integerbody-textcommentable_id-integercommentable_type-string比方说,API正在接收这条新评论:{"body":"Thisatestcomm
在Laravel4中,我有一个“元”模型,可以通过“object_id”和“object_type”属性关联到任何对象。例如:id:1object_id:100object_type:Userkey:favorite_ice_creamvalue:Vanilla我通过morphTo()和morphMany()正常工作,如http://laravel.com/docs/eloquent#polymorphic-relations中所述,所以我可以通过以下方式拉取用户和他的所有元数据:$user=User::with('meta')->find(100);我现在想弄清楚的是:是否有一种简单