您可以在以下代码中解释原因:
#include <iostream>
void fun(char * const & x){(*x)++;}
int main(){
char txt[100]="kolokwium";
fun(txt);
std::cout << txt <<"\n";
}
代码编译需要关键字const吗?
如果我删除它,我会得到:
invalid initialization of non-const reference of type ‘char*&’ from an rvalue of type ‘char*’
谢谢!
答案 0 :(得分:5)
char[100]
的类型为char *
。必须将其转换为fun
才能传递给fun
;此转换会生成 rvalue 。您无法从右值创建非const引用。
为了说明,请考虑如果void fun(char *&x) { x++; }
定义如下,将会发生什么:
char txt[100]="kolokwium";
fun(txt); // Huh?
以下代码会做什么(假设它可以编译)?
directive-a