我们目前存储了几个不同的数据模型集合,如下所示:std::map>>models;字符串映射到一个已知的类型列表,这都是通过序列化处理的。嵌套映射包含“对象ID”和关联(反序列化)std::shared_ptr的集合DataObject是一个基类,我们从中派生出多种类型。我们有一个方法来获取给定类型的所有数据对象:staticstd::map>*getAll(std::stringtype);这只是在给定的“类型”键处返回指向map的指针。今天我遇到了一个代码审查来添加我认为调用UB但似乎起作用的以下内容。这让我有点紧张并寻找有效的解决方案:templatestaticstd::map
通常的克隆习语使用协变返回类型:structBase{virtualBase*clone();};structDerived:publicBase{Derived*clone();};我读过一些东西,大意是协变返回类型是后来添加到C++中的,旧的编译器可能不支持它们。在这种情况下Derived类必须声明它的clone返回Base*的成员函数.因为,据推测,我只访问Derived通过Base的对象使用此习语时的指针和/或引用,声明返回类型的真正用途/好处是什么Derived*?还有一个相关的问题:我更愿意使用智能指针来表达clone的所有权转移语义。签名。这在使用协变返回类型时是不可能的
假设你有这样一个函数:SmartPtrdoSomething(SmartPtra);像这样的类:classA{}classB:publicA{}现在我这样做:SmartPtrfoo=newB();doSomething(foo);现在,我想取回一个SmartPtr来自doSomething的对象.SmartPtrb=doSomething(foo);这可能吗?我需要做什么样的选角?现在,我刚发现一些我认为丑陋的东西:B*b=(B*)doSomething().get()重要说明:我无权访问SmartPtr和doSomething()代码。 最佳答案
如果我有基类:structBase{voidfoo(){bar();}virtualvoidbar(){}};和派生类:structDerived:publicBase{voidbar(){cerr写这段代码的时候会发生:Derivedd;d.foo();我将看到打印“Derivedhere”——因为调用了Derived::bar。但是我没有通过指向基的指针调用,而是在这里工作的多态性。为什么?是不是因为Base::foo中对bar的调用实际上隐式调用了this->bar()和bar在类的vtable中查找? 最佳答案 您的猜测完全
假设我有以下代码:structZ;structA{virtualvoidDo(Z&z)const;};structB:publicA{};structZ{voiduse(Aconst&a){}voiduse(Bconst&b){}};voidA::Do(Z&z)const{z.use(*this);}现在,当我调用B.do,this的类型是A,这是有道理的,因为do的实现在A中定义.有什么方法可以调用B.do使用use(Bconst&)无需为do复制粘贴相同的代码来自A进入B?在我的实际代码中,我有大约15个(并且还在不断增加)派生自某个基类的类,必须为do复制粘贴相同的代码似乎很浪费
来自Wikipedia://TheCuriouslyRecurringTemplatePattern(CRTP)templatestructbase{//...};structderived:base{//...};现在如果我想要derived_from_derived,我可以写://TheCuriouslyRecurringTemplatePattern(CRTP)templatestructbase{//...};templatestructderived:base{//...};structderived_from_derived:derived{//...};现在假设我只想要一
我使用的代码结构有问题,如下(简化):classSPoint{public:SPoint(doublex,doubley,doublez):_x(x),_y(y),_z(z){}protected:double_x,_y,_z;}classPoint3D:publicSPoint{public:Point3D(doublex,doubley,doublez):SPoint(x,y,z){//defaultvaluesforUandV}protected:doubleU,V;}这些点用于创建折线:classSPolyline{public:SPolyline(constvector>&p
includeclassBase{protected:intfoo;intget_foo(){returnfoo;}};classDerived:publicBase{public:voidbar(){intBase::*i=&Base::foo;this->*i=7;printf("foois%d\n",get_foo());}};intmain(){Derivedd;d.bar();}我不明白为什么我的派生类型不能指向基类的protected成员。它有权访问该成员。它可以调用类似作用域的函数。为什么它不能创建一个成员指针?我正在使用gcc4.1.2,但出现此错误:test.cc:I
PreC++11,我问这是否可以使用私有(private)/未实现的技巧(参见here)。显然,这是不可能的。我想知道新的=delete语法是否改变了事态,因为强制派生类不可复制仍然是一个有用的特性。更新后的代码片段可能看起来像这样:classBase{public:Base(){}virtual~Base(){}Base(constBase&)=delete;Base&operator=(constBase&)=delete;virtualvoidinterfaceFunction()=0;//etc.//nodatamembers};classData{/*...*/};class
我很难理解为什么以下代码无法编译:templateclassBase{public:Base(inta){}};templateclassDerived:publicBase{public:Derived(inta):Base(a){}};intmain(){}在我的编译器(gcc5.4.0withC++11)上输出错误信息error:class'Derived'doesnothaveanyfieldnamed'Base'Derived(inta):Base(a){}我看到这有点类似于Templatebaseconstructorcallinmemberinitializationli