jeudi 22 février 2018

Overloading operators for template classes on the heap

I am writing a template class. When I make a version of my class on the stack all the overloaded operators work just as expected. However when I declare the object on the heap none of the overloaded operators work.

in the header file I have:

template <typename K, typename V>
class KeyValue
{
private:
    K key;
    V value;
public:
    KeyValue(K, V);
    virtual ~KeyValue();
    bool operator==(KeyValue<K,V>& rhs)const;
    bool operator!=(KeyValue<K,V>& rhs)const;   
    bool operator<(const KeyValue<K,V>& rhs)const;
    bool operator>(const KeyValue<K,V>& rhs)const;
    KeyValue<K,V>* operator++();
    template <typename k, typename v>
    friend ostream& operator<< (ostream& os, const KeyValue<k,v>& kv);
}

How they are implemented:

template <typename K, typename V>
bool KeyValue<K,V>::operator==(KeyValue<K,V>& rhs)const
{

    if (key == rhs.key)
    {
        return true;
    }
    return false;
}

template <typename K, typename V>
bool KeyValue<K,V>::operator!=(KeyValue<K,V>& rhs)const
{
    if (key != rhs.key)
    {
        return true;
    }
    return false;
}

template <typename K, typename V>
bool KeyValue<K,V>::operator<(const KeyValue<K,V>& rhs)const
{
    if (key < rhs.key)
    {
        return true;
    }
    return false;
}

template <typename K, typename V>
bool KeyValue<K,V>::operator>(const KeyValue<K,V>& rhs)const
{

    if (key > rhs.key)
    {
        return true;
    }
    return false;   
}

template <typename k, typename v>
ostream& operator<<(ostream& os, const KeyValue<k,v>& kv)
{
    os << kv->key << " " << kv->value;
    return os;
}

template <typename K, typename V>
KeyValue<K,V>* KeyValue<K,V>::operator++()
{
    ++value;
    return *this;
}

When I declare this class on the heap everything works how it should, however; If I declare this on the heap like:

KeyValue<string, int> *kv = new KeyValue<string, int>("test", 5);

And then try to increament kv it does nothing. Or if I try to print kv using << operator it just prints off the memory address. I'm new to c++ so I am sure I am doing something wrong I just don't know what. Thank you for any help.

Aucun commentaire:

Enregistrer un commentaire