首页 > 解决方案 > 如何修复错误 C2440: 'return' : cannot convert from 'int' to 'elem *'?

问题描述

我试图构建我的程序,但它一直给我以下错误:

错误 C2440:“return”:无法从“int”转换为“elem *”

问题是我发现修复它的唯一方法是将其更改为 return=0 但这会使整个事情变得毫无意义,因为当我从队列中成功删除一个元素时我希望它返回 1。你知道如何解决它吗?

    struct elem { int key;
        elem *next; 
        } *first=NULL, *last=NULL;   

elem *push(int n, elem *&first, elem *&last)  
    { elem *p=last; 
    last=new elem; 
    last->key=n; 
    last->next=NULL; 
    if(p!=NULL) 
        p->next=last; 
    else 
        first=last; 
    } 

elem *pop(int &n, elem *&first, elem *&las) 
           { elem *p=NULL;
           if (first)  
            {       n=first->key; 
                    p=first;  
                    first=first->next;;

                        if (first==NULL) 
                            last=first;  
                         delete p;
                         return 1;       //this here gives me the error
                }      
                else     
                    return 0;
            }

标签: c++queue

解决方案


c++ 不会让您将整数类型转换为指针,reinterpret_cast否则c-style cast您的函数会产生误导,并且您正在做不应该做的事情。

char *ptr = 1; // error
char *ptr = reinterpret_cast<char*>(0x164651); // compiles but you must make sure this address will be valid !

您声明您的函数返回 anelem *并使其指示成功或失败,在这种情况下,您应该nullptr在失败时返回并在成功时返回指向推送或弹出元素的指针。

elem *pop(int &n, elem *&first, elem *&las) 
           { elem *p=NULL;
           if (first)  
            {       n=first->key; 
                    p=first;  
                    first=first->next;;

                        if (first==NULL) 
                            last=first;  
                         return p;       // return the popped element to the caller
                }      


else     
                return nullptr; // failed to pop any element
        }

如果你坚持用 1 和 0 值来表示成功和失败,那么你应该使用整数类型作为返回类型,而不是指针。

int pop(int &n, elem *&first, elem *&las) // returns 1 on success otherwise 0

在 c++ 中,最好使用异常来指示失败。这允许将故障路径与返回路径分开,并节省大量错误检查,您会发现自己大部分时间都在做这些检查。因此,如果可能,请始终使用 c++ 异常和 RAII,它会为您节省很多。


推荐阅读