简体   繁体   English

错误:无法忽略void值,因为它应该是

[英]error: void value not ignored as it ought to be

template <typename Z> Z myTemplate <Z> :: popFromVector ()
{
    if (myVector.empty () == false)
        return myVector.pop_back ();

    return 0;
}

int main ()
{
    myTemplate <int> obj;

    std :: cout << obj.popFromVector();

    return 0;
}

Error: 错误:

error: void value not ignored as it ought to be

AFAI can see, the return type of popFromVector is NOT void. AFAI可以看到,返回类型popFromVector不为空。 What's the point that I am missing? 我错过了什么意思? The error disappears when I comment out this call in main(). 当我在main()中注释掉这个调用时,错误消失了。

std::vector<T>::pop_back() returns void. std::vector<T>::pop_back()返回void。 You attempt to return it as an int. 您尝试将其作为int返回。 This is not allowed. 这是不允许的。

That is because the definition of std::vector::pop_back has a void return type ... you are trying to return something from that method, which won't work since that method doesn't return anything. 这是因为std::vector::pop_back的定义有一个void返回类型...你试图从该方法返回一些东西,这不起作用,因为该方法不返回任何东西。

Change your function to the following so you can return what's there, and remove the back of the vector as well: 将您的函数更改为以下内容,以便您可以返回其中的内容,并删除向量的背面:

template <typename Z> Z myTemplate <Z> :: popFromVector ()
{
    //create a default Z-type object ... this should be a value you can easily
    //recognize as a default null-type, such as 0, etc. depending on the type
    Z temp = Z(); 

    if (myVector.empty () == false)
    {
        temp = myVector.back();
        myVector.pop_back();
        return temp;
    }

    //don't return 0 since you can end-up with a template that 
    //has a non-integral type that won't work for the template return type
    return temp; 
}

It's the pop_back() . 这是pop_back() It has a void return type. 它有一个void返回类型。 You have to use back() to get the actual value. 您必须使用back()来获取实际值。 This is to avoid unnecessary copies. 这是为了避免不必要的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM