【问题标题】:Relational operator overloading in a templated class (C++)模板类中的关系运算符重载 (C++)
【发布时间】:2011-02-19 23:17:06
【问题描述】:

我正在创建一个 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);
};

这里是

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

这是我测试类功能的主要部分。

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

我在 KeyValuePair 类的

有什么想法吗?提前致谢。

【问题讨论】:

    标签: c++ templates overloading operator-keyword


    【解决方案1】:

    kvp1kvp2 是指向 KeyValuePair&lt;char, int&gt; 对象的指针。它们本身不是KeyValuePair&lt;char, int&gt; 对象。

    *kvp1 &lt; *kvp2 会调用你重载的operator&lt;。您不能为两种指针类型重载operator&lt;,因为将使用内置的指针operator&lt;

    std::pair 可以用作键值对。无论如何,您几乎肯定不应该动态创建这种类型的对象:您应该尽可能避免动态分配,尤其是显式动态分配。相反,只需使用 KeyValuePair&lt;char, int&gt; 局部变量:

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

    【讨论】:

    • 感谢您的帮助!我想让 KeyValuePair 作为一个指针,以便在我将编写的 Dictionary 类中轻松存储。但我明白你的意思。我也不知道 std::pair。我会调查的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2012-11-14
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    相关资源
    最近更新 更多