简体   繁体   中英

How can I retrieve my derived object added to a collection composed of its superclass objects?

I'm dealing right now with this situation where I have a message object composed of a number of fields so I have a map where I load it with objects of the class Field :

std::map<int,Field*> myMsg;

but in my protocol a field can have sequence as a type, so I created a FieldSequence class which inherits from the Field class, and then to add it to my message I did this:

FieldSequence* seqFld=new FieldSequence(sequence);
myMsg[seqFld->id]=seqFld;

but then I needed to retrieve my field in its original sequence format which I know for sure that its id attribute I set it to 0 value. so I did this:

std::map<int,Field*>::iterator it;
for ( it=myMsg.begin() ; it != myMsg.end(); it++ )
{

    cout << "field id => " << (*it).first <<  endl;
    int idprm=((*it).second)->id;
    if(idprm==0)
    {
        FieldSequence* temp=(*it).second;
    }
}

but I have error due to this Conversion, so what can I do to retrieve my original format or is it gone for good once I add it to my map as it's superclass format?

You can use dynamic_cast and check the result:

FieldSequence* temp = dynamic_cast<FieldSequence*>(it->second);
if (temp) { 
  // do stuff
}

But generally this is a sign that you should reconsider the design. It doesn't scale very well if you have many derived types and need to check them all. Containers of pointers to base classes are most powerful when all the derived types implement the same interface and have no additional methods.

This is very common problem. The actual problem is not "getting derived class" out of the Field* pointers. The real problem is that your Field class' interface cannot properly represent behaviour of all it's derived classes. One alternative would be this:

class Field {
public:
     virtual std::string ContentsAsString() const=0;
};

Another would be something like this:

class Field {
public:
    virtual char *Buffer() const=0;
    virtual int BufferSize() const=0;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM