堆上的模板类超载运算符

Overloading operators for template classes on the heap

本文关键字:超载 运算符      更新时间:2023-10-16

我正在编写模板类。当我在堆栈上制作班级版本时,所有超载运算符的工作正常。但是,当我在堆上声明对象时,没有一个过载的操作员工作。

在标题文件中我有:

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);
}

它们的实施方式:

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;
}

当我在堆上声明此类时,一切应如何工作;如果我在堆上声明:

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

,然后尝试将kV递增,它无能为力。或者,如果我尝试使用<<运算符打印KV,则只需打印出内存地址即可。我是C 的新手,所以我确定我做错了什么,我不知道什么。谢谢您的帮助。

您已将该类声明为KeyValue<string, int> *kv

这里的星号表示您正在声明指针。

这意味着您要声明变量kv指向KeyValue对象。打印kv时,它会打印指向的KeyValue对象的地址。

在这种情况下,您使用返回指针的new关键字。因此,您需要使用星号并访问对象本身,您需要首先取消指针(John说(*kv)++cout << *kv都应该工作(。

您可以阅读指针的使用以及它们在这里的工作方式:Pointers

另外,不要使用指针。