C++ 错误:没有忽略无效值,因为它应该是

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7307830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:46:15  来源:igfitidea点击:

error: void value not ignored as it ought to be

c++vector

提问by Aquarius_Girl

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 popFromVectoris NOT void. What's the point that I am missing? The error disappears when I comment out this call in main().

AFAI 可以看到,返回类型popFromVector不是 void。我失踪的重点是什么?当我在 main() 中注释掉这个调用时,错误消失了。

采纳答案by Puppy

std::vector<T>::pop_back()returns void. You attempt to return it as an int. This is not allowed.

std::vector<T>::pop_back()返回无效。您尝试将其作为 int 返回。这是不允许的。

回答by Jason

That is because the definition of std::vector::pop_backhas a voidreturn 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; 
}

回答by ltjax

It's the pop_back(). It has a void return type. You have to use back()to get the actual value. This is to avoid unnecessary copies.

这是pop_back(). 它有一个 void 返回类型。您必须使用back()来获取实际值。这是为了避免不必要的副本。