我知道这可能是以下内容的重复:如果未找到搜索结果,则返回“NULL”对象 https://stackoverflow.com/questions/2639255/c-return-a-null-object-if-search-result-not-found
但是,我的代码出现了一些不同的情况,因为星号不能解决我的问题,即:
Normal Sphere::hit(Ray ray) {
//stuff is done here
if(something happens) {
return NULL;
}
//other stuff
return Normal(something, somethingElse);
}
但我在引用时遇到错误return NULL
line: conversion from ‘int’ to non-scalar type ‘Normal’ requested
另一个错误和警告引用最后一个返回行:warning: taking address of temporary
and conversion from ‘Normal*’ to non-scalar type 'Normal' requested
我明白为什么会收到此警告,但我不知道如何解决它。我如何返回Normal
函数结束后最后一行中的对象仍然存在,以及如何返回NULL
第一次反对? (如果有针对此类回报的术语,请告诉我,以便我也可以阅读更多内容。)
为了澄清评论者的问题,我尝试了以下方法:
我尝试这样做:Normal *Sphere::hit(Ray ray)
在 cpp 文件中和Normal *hit( Ray ray );
在头文件中,我收到此错误:error: prototype for ‘Normal* Sphere::hit(Ray)’ does not match any in class 'Sphere'
我也尝试过这个:Normal Sphere::*hit(Ray ray)
在 cpp 文件中和Normal *hit( Ray ray);
在头文件中,我在第二个 return 语句中收到此错误:cannot convert 'Normal*' to 'Normal Sphere::*' in return
进一步澄清:我不是在问指针如何工作。 (这不是主要问题。)我想知道有关 C++ 中指针的语法。因此,鉴于我上面指定的函数,我发现我应该指定返回指针,因为 C++ 没有空对象。知道了。但是,问题就变成了:函数原型应该是什么样子?在 cpp 文件中,我有 Bala 的建议(这是我最初的建议,但由于以下错误而更改了它):
Normal* Sphere::hit(Ray ray) {
//stuff is done here
if(something happens) {
return NULL;
}
//other stuff
return new Normal(something, somethingElse);
}
在头文件中,我有Normal *hit(Ray ray)
,但我仍然收到此消息:prototype for 'Normal* Sphere::hit(Ray)' does not match any in class 'Sphere'
目前,我不清楚为什么它找不到该函数原型。这是头文件:
class Sphere
{
public:
Sphere();
Vector3 center;
float radius;
Normal* hit(Ray ray);
};
谁能明白为什么它抱怨不存在匹配的原型hit
in the Sphere
班级? (我可能会将其移至一个单独的问题......)