简体   繁体   中英

error: cannot initialize return object of type 'Type *' with an rvalue of type 'bool'

I have this code in JavaScript:

// ...

 findNode: function(root, w, h) {
    if (root.used)
      return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
},

// ...

I'm developing an equivalent code in C++ like this:

Block *GrowingPacker::findNode(Block *root, float w, float h)
{
    if (root->m_used)
        return findNode(root->m_right, w, h) || findNode(root->m_down, w, h);
}

However C++ throws this error at return line:

error: cannot initialize return object of type 'Block *' with an rvalue of type 'bool'

I wonder what is the most elegant approach to prevent the error!

if (root->m_used)
    return findNode(root->m_right, w, h) || findNode(root->m_down, w, h);

returns a boolean but your function expects to return a Block* . In Javascript it doesn't matter because there is no strong typing but in C++ the return type of || is bool .

I think you want this

if (root->m_used)
{
    Block* tmp = findNode(root->m_right, w, h);
    if (tmp)
        return tmp;
    else
        return findNode(root->m_down, w, h);
}

AND you need to add some code to deal with the case when root->m_used is false ( return nullptr; presumably).

Unlike Javascript, C++ is a strongly typed language. Therefore it's really important to enable all the warnings you can on your compiler, so you can catch as many type mismatches and other gotchas as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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