這聽起來像你想要一個「可選」返回參數。您似乎(並且正確地)將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