mardi 6 octobre 2020

how to store polymorphic object in set

how to define overloaded comparison operator or comparison functor, so that i can create the set of class A. i have a class Base which have int member variable _state and a derived class A.

#include <vector>
#include <set>
class Base{
int _state;
protected:
    virtual void fun() = 0;
public:
bool operator < (const Base & t)
{
return (this->_state < t._state);
}
    Base (int s): _state(s){}
    virtual ~Base() = default;
};

class A: public Base{
public:
    A(int s): Base(s){}
    void fun() override{}
    
};

int main()
{
    A a(5);
    
    std::set<A> s;
    
    s.insert(a);
    
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire