在c ++中使用自定义字符串类作为映射键值

时间:2018-02-12 02:31:15

标签: c++ string dictionary key operator-overloading

当我尝试使用自定义字符串类作为键值时,我看到此错误

undefined reference to `operator<(DSString const&, DSString const&)'

我已经超载了&lt;运算符,但它只允许我用一个参数,而不是两个参数。我读了一个与此类似的问题,但我无法使任何解决方案起作用。

bool DSString::operator< (const DSString& newData){
    bool lessThan = true;
    int counter = 0;
    int dataLetter = 0;
    int newDataLetter = 0;

    //compare each letter of both Strings until they differ,
    while(dataLetter == newDataLetter && counter < this->length){
        dataLetter = static_cast<int>(data[counter]);
        newDataLetter = static_cast<int>(newData.data[counter]);
         //change bool if char of current stirng is greater
        if(dataLetter < newDataLetter)
            lessThan = true;
        else if (dataLetter > newDataLetter)
            lessThan = false;
    }

    return lessThan;
}

1 个答案:

答案 0 :(得分:0)

您的会员运营商要求左侧(即this指针指定的那个)不是 - const。在声明中添加const将解决问题:

bool DSString::operator< (const DSString& newData) const;

while循环的实现不正确:运算符返回的值对应于最后的比较结果。一旦发现差异,正确的实施应该返回truefalse;只有当相应位置的字符相同时,循环才会继续。此外,当到达两个字符串的较短的末尾时,循环应该停止;当this字符串用完字符时,当前实现停止,当另一个字符串更短时,导致未定义的行为。

Demo.