模板化类中的关系运算符重载(C++)

1 c++ templates overloading operator-keyword

我正在创建一个KeyValuePair类,并在重载关系运算符时遇到一些麻烦.我的理解是,这对于使用std排序函数是必要的(我试图根据值进行排序)

这是标题:

template <typename K, typename V>
class KeyValuePair
{
public:
    //factory
    static KeyValuePair<K,V>* newKeyValuePair(K key, V value);  
    //getters
    const K &Key() const;
    const V &Value() const;
    //setter
    V &Value();

    //The problem
    bool operator<(const KeyValuePair<K,V> &rhs);

    string toString();
    ~KeyValuePair(void);
private:
    K key;
    V value;
    KeyValuePair(K key, V value);
    KeyValuePair(void);
};
Run Code Online (Sandbox Code Playgroud)

这是<function的定义

template <typename K, typename V>
bool KeyValuePair<K,V>::operator<(const KeyValuePair<K,V> &rhs)
{
    return value < rhs.Value();
}
Run Code Online (Sandbox Code Playgroud)

这里是我正在测试类的功能的主要部分.

int _tmain(int argc, _TCHAR* argv[])
{
    KeyValuePair<char,int>* kvp1 = KeyValuePair<char, int>::newKeyValuePair('A',1);
    KeyValuePair<char,int>* kvp2 = KeyValuePair<char,int>::newKeyValuePair('B',10);
    cout << (kvp1 < kvp2) << "\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在KeyValuePair类的<function中有一个断点,它永远不会被激活.

有任何想法吗?提前致谢.

Jam*_*lis 5

kvp1并且kvp2是指向KeyValuePair<char, int>对象的指针.它们本身不是KeyValuePair<char, int>对象.

*kvp1 < *kvp2会调用你的重载operator<.您不能operator<为两个指针类型重载,因为operator<将使用指针的内置.

std::pair可以用作键值对.在任何情况下,您几乎肯定不应该动态创建此类型的对象:您应该尽可能避免动态分配,尤其是显式动态分配.相反,只需使用KeyValuePair<char, int>局部变量:

KeyValuePair<char, int> kvp1('A', 1);
KeyValuePair<char, int> kvp2('B', 10);
std::cout << (kvp1 < kvp2) << "\n"; // calls your operator< overload
Run Code Online (Sandbox Code Playgroud)