这听起来像你想要一个“可选”返回参数。您似乎(并且正确地)将0.0用作“无值”结果,因为这意味着0.0不能用于实际值。
您有时看到的两个很好的解决方案是使用“结果代码”,或使用指针作为返回结果。 (指针更复杂)。我会用#1先启动:
1.结果代码
// definitions for result codes
#define FAIL 0
#define OK 1
int GetNewValue(int feature, double *result) {
switch(feature) {
case TYPE1:
*result = 0.0 ;
return FAIL ; // caller of the function should recognize
// the call "failed"
case TYPE2:
*result = 200.0 ;
return OK ;
default:
*result = 47.0 ;
return OK;
}
}
// use:
double feature ;
int result = GetNewValue(5, &feature) ;
if(result == OK)
{
// do something with "feature"
}
2.使用指针
double* GetNewValue(int feature) {
switch(feature) {
case TYPE1:
return NULL ; // NO POINTER means FAIL
case TYPE2:
return new double(200) ;
default:
return new double(47) ;
}
}
// use:
double* result = GetNewValue(5) ;
if(result != NULL)
{
// result had a value, so you can use it
}
与指针的小问题,就是你需要记住的delete
result
delete result ; // when done with pointer that was created
// with `new`, you must `delete` it after
// otherwise you'll get a memory leak
你可以使用'NaN'。 'void'是没有意义的,因为它类似于类型,而不是值。 – CodesInChaos 2013-05-06 15:26:28
但是,我该如何检查它?是否可能影响一个变量并检查返回的值是否为空? – gaborous 2013-05-06 15:27:22
btw。有许多不同的NaN。原则上你可以使用不同的NaN来表达不同的意思,但这可能是一个坏主意。 – CodesInChaos 2013-05-06 15:28:03