堆上的模板类超载运算符
Overloading operators for template classes on the heap
我正在编写模板类。当我在堆栈上制作班级版本时,所有超载运算符的工作正常。但是,当我在堆上声明对象时,没有一个过载的操作员工作。
在标题文件中我有:
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
另外,不要使用指针。
相关文章:
- 虚拟超载运算符>>和<<
- 为什么我的超载"+"运算符返回的总额错误?
- 我可以防止与null与超载运算符==进行比较
- 超载 运算符添加const char
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 堆上的模板类超载运算符
- 我想将超载运算符添加到派生类中
- 超载 *运算符时无法转换错误
- 在将对象声明为挥发性时,如何在C 中超载运算符
- 超载运算符*与操作员双重模棱两可()
- 在C 中的超载运算符中使用局部变量
- 如何使用超载 运算符组合两个链接列表
- C 超载 运算符,因此您可以在该类中添加不同的类并获得第三类
- 超载运算符== C 时获取SigSeGV(分割故障)
- 超载运算符=在单链接列表中
- 超载 运算符在C 中加入两个字符串(一些疑问)
- 使用超载运算符添加构造函数
- 为什么在C 中调用模板超载运算符时,我会遇到细分故障
- 是否可以超载[]运算符在不定义类的情况下访问特定的字符
- 没有可行的超载运算符[]