C++ 如何返回空字符引用
如何返回空值?我创建了一个设置为null的本地字符…但是有没有其他方法返回null左值C++ 如何返回空字符引用,c++,null,char,operator-overloading,C++,Null,Char,Operator Overloading,如何返回空值?我创建了一个设置为null的本地字符…但是有没有其他方法返回null左值 char& String::operator[](int index) { char s = NULL; if (index > length) { cout << "Incorect index. Enter an index 0 through (String length -1)." <<endl; return
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 {
}
}
char&String::operator[](int-index){
chars=NULL;
如果(索引>长度){
cout您可以返回'\0'
。这可能接近您的意图。如果您的意图是函数应始终返回有效引用(在本例中为空字符),则可以使用静态变量
static char s;
s = 0; // must do this every time in case the receiver modified the value last time
return s;
引用永远不应该为NULL。使用指针。我认为你问的问题是错误的。我认为你不想返回对NULL字符的引用。首先,你不应该将char
s本身设置为NULL
。其次,你不应该返回对局部变量的引用。在这种情况下,你应该抛出一个异常。为什么返回对char
的引用而不是没有引用的char
?类型char
不够大,无法保证通过引用传递(另外,值必须是静态的)。它不应该是s='\0'
?s=NULL
使它看起来像s
是一个指针,而它不是。@DrewMcGowen,任何一个都可以工作,NULL
宏被定义为0
。但你是对的,它传达了一个错误的假设,所以我会更改它。