[英]Error: Initial value of reference to non-const must be an lvalue
Getting another error with my string class. 我的字符串类出现另一个错误。 The intellisense will not let me use strcmp to compare an object with the self-invoking object (ie *this). 智能感知不会让我使用strcmp将对象与自调用对象(即* this)进行比较。
I tried making my own operator conversion function to help with this, but it is still giving me the error. 我尝试制作自己的运算符转换函数来帮助解决此问题,但仍然给我错误。
What do I have to change in my code to make this work?? 为了使这项工作有效,我必须对代码进行哪些更改?
//Overloaded comparison operators
bool &String::operator<(const String & obj)
{
return strcmp(*this, obj) < 0 ? true : false;
}
//Operator conversion function
String::operator char const * () const
{
return mStr;
}
You are returning a reference to a local variable. 您正在返回对局部变量的引用。 Return by value. 按值返回。 You can also simplify the return expression, and make the method const
, since comparing two objects should not change either of them: 您还可以简化return表达式,并使方法成为const
,因为比较两个对象不应更改它们中的任何一个:
bool String::operator<(const String & obj) const {
return strcmp(*this, obj) < 0;
}
although I am not sure
strcmp
can deal with two
String
s, which is what you are passing it.
尽管我不确定
strcmp
可以处理两个
String
,但这是您要传递的内容。
Judgning from your previous question, you need
从上一个问题判断,您需要
return strcmp(mstr, obj.mStr) < 0;
Make it const
and remove &
将其设为const
并删除&
bool String::operator<(const String & obj) const
^^^^^
Returning references to temporary objects leads to undefined behavior. 返回对临时对象的引用会导致未定义的行为。
错误消息显式指向strcmp()
第一个参数,*这是一个右值,但是strcmp需要一个左值,请尝试在前面添加一个句子:
String thisObj = *this;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.