c++ - 如何修复错误 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++ 不会让您将整数类型转换为指针,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,它会为您节省很多。
推荐阅读
- ios - 在标签上打印 instgram 回复时出现问题
- android - 使用 mqtt 发送推送通知,从最近的应用程序中滑动时不起作用
- stripe-payments - 用条纹测试谷歌支付
- ios - 在 iOS 10 上从自定义键盘打开设置应用程序时崩溃
- c# - 如何为另一个类的测试参数设置 IEqualityComparer?
- html - overscroll-behavior 属性不适用于 webview
- docker - 节点 API 失败并出现错误:EHOSTUNREACH
- assembly - S1.geti、S2.geti 都调用同一个过程(称为 Sc_geti)。S1.i 不可用。奇怪的字符
- javascript - 在 parseFloat() 之后将对象键数组中的所有值相加
- javascript - 无法选中第二个循环内的复选框