具有*&功能的Const关键字论点。

时间:2015-06-14 17:05:10

标签: c++ const pass-by-reference

您可以在以下代码中解释原因:

    #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*’

谢谢!

1 个答案:

答案 0 :(得分:5)

char[100]的类型为char *。必须将其转换为fun才能传递给fun;此转换会生成 rvalue 。您无法从右值创建非const引用。

为了说明,请考虑如果void fun(char *&x) { x++; } 定义如下,将会发生什么:

char txt[100]="kolokwium";
fun(txt);                      // Huh?

以下代码会做什么(假设它可以编译)?

directive-a