错误C2106:'=':左操作数必须是l值 [英] error C2106: '=' : left operand must be l-value

查看:248
本文介绍了错误C2106:'=':左操作数必须是l值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看关于错误C2106的其他问题,我仍然失去了关于我的代码的问题。编译时会出现以下错误:

Looking at the other questions regarding error C2106, I am still lost as to what the issue is with my code. While compiling I get the following errors:


c:\driver.cpp(99):error C2106:'=':left operand必须是l-value

c:\driver.cpp(99): error C2106: '=' : left operand must be l-value

c:\driver.cpp(169):error C2106:'=':left operand必须是l-value

c:\driver.cpp(169): error C2106: '=' : left operand must be l-value

代码行如下:

        payroll.at(i) = NULL; //Line 99
        payroll.at(count++) = ePtr; //Line 169

我无法理解为什么会抛出此错误。在这个项目中,我已经将我的driver.cpp从一个employee对象指针数组更改为一个自定义的Vector模板。我声明的向量如下...

I am failing to understand why this error is being thrown. In this project I have changed my driver.cpp from an array of employee object pointers to a custom Vector template that I made. I declare the Vector as follows...

//Declare an Vector to hold employee object pointers
MyVector <employee*> payroll;

任何帮助...

推荐答案

这个错误被抛出的原因是你不能这样做:

This error is being thrown for the same reason you can't do something like this:

36 = 3;

您的 Vector :: at 返回引用而不是值。

L值称为L值,因为它们可以出现在作业的左侧。 Rvalues不能出现在左侧,这就是为什么我们把它们称为右值。您不能将 3 分配给 36 ,因为 36 不是一个左值,它是一个右值,一个临时的。它没有内存地址。出于同样的原因,您不能将 NULL 分配给 payroll.at(i)

Your version of Vector::at should be returning a reference rather than a value.
Lvalues are called Lvalues because they can appear on the left of an assignment. Rvalues cannot appear on the left side, which is why we call them rvalues. You can't assign 3 to 36 because 36 is not an lvalue, it is an rvalue, a temporary. It doesn't have a memory address. For the same reason, you cannot assign NULL to payroll.at(i).

您的定义:

template <class V> V MyVector<V>::at(int n)

应该是什么:

template<typename V> V& MyVector::at(std::size_t n)
template<typename V> const V& MyVector::at(std::size_t n) const

这篇关于错误C2106:'=':左操作数必须是l值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆