简体   繁体   中英

How to add a method to a superclass from a subclass in C++

What I have:
Vectors of different custom structs(one custom struct per vector)
I used pointers to each struct to give it a static size per record
A vector that combines these vectors via a pointer to each
When I try to cast a pointer to the custom vector it fails on every iteration
My workaround is a call to a function that takes the vector pointer as an argument and returns a void pointer.
I know this is wrong despite being functional, but I can't find a reference on the right way to define the cast method properly.

I'm looking for the right way to accomplish this.

typedef struct mystruct {
    DWORD something;
    vectorclassa * somethinga;
    vectorclassb * somethingb;
    };

typedef std::vector&ltmystruct*> amystruct;
void * theWrongWay(mystruct * apointer){
    return apointer;
}

typedef std::vector bigvector;

If I try to bigvector.push_back(&instance_of_amystruct)
It fails. If I change std::vector<amystruct*> bigvector to a void* and call theWrongWay with a &amystruct instance, it compiles/runs. It just seems wrong.

The problem is that I don't know how to define the missing method for vector or cast it to something vector knows how to deal with without doing something...bad.

It's very hard to answer this question because it's hard to tell why you want to do this. Why do you want to keep vectors of different types in another vector?

Anyway, I'll just assume that you want to do this because there's some common action you want to take on each vector. Then you can simply define an abstract class that defines that action, and have a templated child class of this class that keep a different vector depending on the template argument. You can then keep the vectors in a container referring to them as their common ancestor. Some code:

class ActionableVector {
   virtual void doSuperCoolStuff() = 0;
}

template<typename T>
class VectorHandler: public ActionableVector {
    vector<T> handledVector;
    // vector<T> & handleVector; // You can keep a reference to an external vector too
    virtual void doSuperCoolStuff() {
        //do super cool stuff in a type-safe manner
    }
}

template<>
class VectorHandler<ATypeThatNeedsSpecialAttention>: public ActionableVector {
    Vector<ATypeThatNeedsSpecialAttention> handledVector;
    virtual void doSuperCoolStuff() {
         // Do especially cool stuff
    }

vector<ActionableVector*> myVectors;

for(ActionableVector * av: myVectors ) { //C++ 11 yaay
    av->doSuperCoolStuff();
}

If you really really really want to keep objects of completely different types in a container, and willing to sell your soul to the devil for that, look at this answer.

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