您能否在以下代码中解释原因:
#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*’
谢谢!
txt
是类型char[100]
。必须将其转换char *
为才能传递给fun
;此转换产生右值。您不能从右值创建非常量引用。
为了说明,请考虑如果fun
定义如下会发生什么:
void fun(char *&x) { x++; }
以下代码会做什么(假设可以编译)?
char txt[100]="kolokwium";
fun(txt); // Huh?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句