如何在C++派生对象的集合中进行搜索和赋值

How can I search through and assign from a collection of C++ derived objects?

本文关键字:搜索 赋值 集合 C++ 派生 对象      更新时间:2023-10-16

我的问题的技术部分得到了很好的答案,即为什么我目前的方法不起作用(将derived**分配给base**是不安全的类型,另请参阅将派生**转换为Base**和将派生*转换为Base*)。然而,我仍然不知道如何以C++的方式实现我的想法。我开始问一个新问题,因为上一个标题太具体了。

以下也许是我想要做的事情的一个更清晰的解释:

  1. 创建多个对象,这些对象都是从一个类派生的类的实例
  2. 将这些对象与编译时人类可读的标识符(可能是字符串?)一起存储在某种类型的主容器中
  3. 从其他组件获取标识符列表,搜索主容器,并将它们传回(指向的指针/引用)相应的对象,以便它们可以读取/修改它们。在这一点上,我认为我需要打破类型安全性,并假设组件通过标识符知道他们所要求的派生类型

我认为这将相对简单和优雅地处理映射、向量和指向对象的指针(我在上一个问题中给出了一个简化的例子),但似乎我必须进行大量的C样式类型转换,以允许组件将指针传递到存储主容器值的位置。这向我表明,我没有遵循C++范式;应该";我知道吗?

[编辑]以下是我如何设想的一些假设示例代码,希望这能澄清我的想法:

#include <map>
#include <vector>
#include <string>
using namespace std;
class BaseObj {};
class Der1Obj: public BaseObj {};
class Der2Obj: public BaseObj {};
typedef map<string, BaseObj**> ObjPtrDict;
typedef map<string, BaseObj*> ObjDict;
class BaseComp
{
public:
   ObjPtrDict objs;
};
class DervComp
{
   DervComp(){objs["d1"] = &d1; objs["d2"] = &d2; } // This wouldn't compile
   Der1Obj* d1;
   Der2Obj* d2;
}
typedef vector<BaseComp*> CompList;
void assign_objs(CompList comps, ObjDict objs)
{
   for (auto c = comps.begin(); c != comps.end(); c++)
     for (auto o = c.objs.begin(); o != c.objs.end(); o++)
       *(o->second) = objs[o->first];
}
int main(int argc, char* argv[])
{
    Der1Obj d, d1;
    Der2Obj d2;
    ObjDict objs;
    objs["d"] = &d;
    objs["d1"] = &d1;
    objs["d2"] = &d2;
    DervComp c;
    vector<DervComp*> comps;
    comps.push_back(&c);
    assign_objs(comps, objs);
    return 0;
}

如果我得到了你想要的,你可以这样做:

#include <vector>
class Base
{
public:
    enum eDerived
    {
    //name these whatever you like
        DER1,//for first derived class
        DER2,//for second derived class
        DER3//for third derived class
    };
    virtual eDerived type() = 0;//this will return the class type.
};
class Derived1: public Base
{
public:
    virtual eDerived type() { return DER1; }
};
class Derived2: public Base
{
public:
    virtual eDerived type() { return DER2; }
};
class Derived3: public Base
{
public:
    virtual eDerived type() { return DER3; }
};
int main()
{
    std::vector<Base*> myList;//container for all elements
    //You can store a pointer to any of the derived classes here like this:
    Base * a = new Derived1();
    Base * b = new Derived2();
    Base * c = new Derived3();
    myList.push_back(a);
    myList.push_back(b);
    myList.push_back(c);
    //Iterating through the container
    for( Base * tmp: myList)
    {
        //You can check the type of the item like this:
        if( tmp->type() == Base::DER1 )
        {  
            //and cast to a corresponding type.
            //In this case you are sure that you are casting to the right type, since
            //you've already checked it.
            Derived1 * pointerToDerived1 = static_cast<Derived1 *>(tmp);
        }
    }
}

Ofc你可以选择任何类型的容器。如果要给它们一个ID,可以使用map,也可以将其添加到类本身中。

我读过你的另一篇文章,但我想我不明白你为什么要使用双指针。根据我的理解,你只需要使用一个普通的指针。

例如

class Base
{
};
class Deriv : public Base
{
};
std::map< std::string, Base* > ObjectStore;
function Component1( ... )
{
   Base* b = ObjectStore[ "MyObject" ];
   b->DoSomeFancyStuff();
}
function ModifyObjectStore( )
{
   delete ObjectStore[ "MyObject" ];
   ObjectStore[ "MyObject" ] = new Derived(); 
}

我希望这能有所帮助。

您说,"将它们传递回相应的对象"。为此,你为什么要把基地传回来**?您可以简单地返回从字符串到指针的映射。请参阅下面的代码进行解释。

class Container
{
    void add(const string& aKey_in, Base* b)
    {
        myObjects[aKey_in] = b;
    }
    void getObjs(list<string> aKeys_in, map<string,Base*>& anObjMap_out)
    {
        for(all string s in the aKeys_in)
            anObjMap_out[s] = myObjects[s];
    }
private:
    map<string, base*> myObjects;
};

您的条件符合以下条件:创建多个对象,这些对象都是从一个类派生的类的实例您可以将类扩展为具有创建逻辑、工厂逻辑等。

将这些对象与编译时人类可读的标识符(可能是字符串?)一起存储在某种类型的主容器中使用地图实现

从其他组件获取标识符列表,搜索主容器,并将它们传回(指向的指针/引用)相应的对象,以便它们可以读取/修改它们。在这一点上,我认为我需要打破类型安全性,并假设组件通过标识符知道他们所要求的派生类型

您不需要将指针对指针传递回客户端。只需将对象指针传回即可。

附加说明:您可以使用shared_ptr而不是原始指针来实现指针。如果您的客户端代码(使用getObjs()方法的用户)编写正确,那么就不需要从基指针到派生指针的动态转换。它们应该能够使用基指针。不管怎样,这是一个不同的问题,你还没有问。