C ++(E0158表达式必须是左值或函数指示符)和(错误C2102'&'需要左值)

时间:2019-07-05 16:02:15

标签: c++ pointers reference copy

在我的家庭作业中,我获得了为prefix_vector创建一个类的任务,因此主要工作无需进行任何修改。

我总是遇到错误:

  

E0158表达式必须为左值或函数指示符

  

错误C2102'&'需要左值

如何做到这一点而没有任何编译错误?

template <class T>
class prefix_vector
{
public:
    prefix_vector(std::vector <T>& x) :vpre{ x }
    {
    }
    void push_back(const T & t)
    {
        for (unsigned int i = 0; i < vpre.size(); i++)
        {
            if (t == vpre[i])
            {
                vpre.erase(vpre.begin() + i);
            }
        }
        vsuf.push_back(t);
        for (int i = 1; i < vsuf.size(); ++i)
        {
            for (int j = 0; j < vsuf.size() - 1; ++j)
            {
                if (vsuf[j] > vsuf[i]) std::swap(vsuf[j], vsuf[i]);
            }
        }
    }
    T  at(const T &  x)
    {
        std::vector <T> vpresu = vpre;

        for (int i = 0; i < vsuf.size(); i++)
        {
            vpresu.push_back(vsuf[i]);
        }
        return vpresu[x + vsuf.size()];
    }

    int size() const
    {
        return vsuf.size();
    }

private:
    std::vector <T> & vpre;
    std::vector <T> & vsuf;
};


const int max = 1000;

int main()
{
    std::vector<int> v;
    for (int i = 0; i < max; ++i)
    {
        v.push_back(i);
    }

    prefix_vector<int> p(v);
    prefix_vector<int> a(p);
    prefix_vector<int> b(p);
    prefix_vector<int> c(p);

    a.push_back(2);
    b.push_back(4);
    c.push_back(8);
    c.push_back(1);

    std::vector<std::string> s;
    s.push_back("Hello");
    prefix_vector<std::string> sh(s);
    prefix_vector<std::string> sa(sh);
    sa.push_back("World");
    prefix_vector<std::string> sb(sh);


    if (8 == c.at(max) && &(a.at(max / 2)) == &(b.at(max / 2)) &&
        a.size() == b.size() && 1 == p.at(1) && 4 == b.at(max) &&
        &(b.at(max - 1)) == &(c.at(max - 1)) &&
        &(b.at(max)) != &(c.at(max)) && 1 == sb.size() &&
        1 == sh.size() && "Hello" == sa.at(0))
    {
        std::cout << "you did great" << std::endl;
    }
}

我明白了

  

E0158表达式必须为左值或函数指示符

     

错误C2102'&'需要左值

输出应为:

you did great

2 个答案:

答案 0 :(得分:1)

此错误:

Map.Entry

表示您试图获取非法的临时地址(在本例中为r值)。在某个对象上使用E0158 expression must be an lvalue or a function designator Error C2102 '&' requires l-value 意味着获取其地址-因此它必须存在于内存中的某个位置。 l值是可能存储在CPU寄存器中的对象,因此获取其地址没有意义。

在您的情况下,您尝试比较地址而不是值,而不是:

&

您应该:

&(a.at(max / 2)) == &(b.at(max / 2))
^                   ^

修复它之后,您可能还会发现许多其他错误,但是我想您可以自己处理它们。

答案 1 :(得分:0)

at会返回矢量中对象的临时副本。您无法获得指向临时对象(或“ r值”)的指针,因此&(a.at(max / 2))会产生错误。

我不确定您要测试什么,但是我猜(a.at(max / 2)!= 0)是正确的语法。

或者更改at以返回引用,然后可以获取指向的引用。