当我尝试使用我的自定义字符串类作为键值时,我看到了这个错误
undefined reference to `operator<(DSString const&, DSString const&)'
我已经重载了 < 运算符,但它只允许我使用一个参数来执行此操作,而不是两个。我读到一个与此类似的问题,但我无法找到任何解决方案。
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;
}
最佳答案
您的成员运算符要求左侧(即由 this
指针指定的那一侧)是非 const
。将 const
添加到声明中将解决问题:
bool DSString::operator< (const DSString& newData) const;
您对 while
循环的实现不正确:您的运算符返回的值对应于最后的比较结果。一旦发现差异,正确的实现应该立即返回 true
或 false
;仅当相应位置的字符相同时,循环才应继续。此外,当到达两个字符串中较短 的末尾时,循环应该停止;当 this
字符串用完字符时,您当前的实现将停止,当另一个字符串较短时会导致未定义的行为。
关于c++ - 在 C++ 中使用自定义字符串类作为映射键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738784/