2013-07-24 56 views
1

如何返回空值?我創建了一個本地字符集爲空...但有沒有不同的方式來返回一個空的左值?如何返回空char參考

char& String::operator[](int index) { 
    char s = NULL; 
    if (index > length) { 
     cout << "Incorect index. Enter an index 0 through (String length -1)." <<endl; 
     return s; // how do i return null value...this is local... 
    } 
    else { 
    } 
} 
+1

拋出異常。 – chris

+0

引用永遠不應該是NULL。使用指針。 – Jacob

+0

我想你問的是錯誤的問題。我不認爲你想要返回一個空字符的引用。 –

回答

1

如果你的意圖是功能應該總是返回一個有效的引用(在這種情況下爲一個空字符),那麼你可以使用一個靜態變量。

static char s; 
s = 0; // must do this every time in case the receiver modified the value last time 
return s; 
+1

不應該是's ='\ 0''嗎? 's = NULL'使它看起來像's'是一個指針,它不是。 –

+0

@DrewMcGowen,任何一個都可以工作,無論如何'NULL'宏定義爲'0'。但是你說得對,它傳達了一個不正確的假設,所以我會改變它。 –

1

您可能會返回'\0'。這可能會接近你的意圖。