简体   繁体   English

错误:对非常量的引用的初始值必须为左值

[英]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.

相关问题 出现错误:对非常量的引用的初始值必须是左值 - getting error: initial value of reference to non-const must be an lvalue 非常量引用的初始值必须是左值 - initial value of reference to non-const must be an lvalue 错误:非常量的初始值必须为左值 - Error: Initial value to non-const must be an lvalue 从对象调用成员对象,错误:对非常量引用的初始值必须是左值 - Call member object from object, ERROR: initial value of reference to non-const must be an lvalue C++ 如何修复错误“对非常量引用的初始值必须是左值”? - C++ How to fix error "initial value of reference to non-const must be an lvalue"? 函数作为参数的C ++错误,对非const的引用的初始值必须是左值 - C++ error with functions as parameters, initial value of reference to non-const must be an lvalue C++ 在这种情况下,“引用非常量的初始值必须是左值”的错误是什么意思? - C++ what does the error of "Initial value of reference to a non-const must be an lvalue" mean in this case? 错误:对非const的引用的初始值必须是一个值 - Error: initial value of reference to non-const must be an value 需要进一步说明:引用非const的初始值必须为左值 - Further Explanation needed: Initial value of reference to non-const must be a lvalue 将 opencv Mat 传递给函数时,对非常量的引用的初始值必须是左值 - Initial value of reference to non-const must be an lvalue when passing opencv Mat to a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM