函数中的 Const 关键字带有 *&参数。

Const keyword in function with an *& argument.

本文关键字:参数 Const 关键字 函数      更新时间:2023-10-16

你能在下面的代码中解释一下原因吗:

    #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?